|
30鱼币
使用了墨迹天气的api想要查询天气,里面给出了请求实例使用python2写的如下:
- import urllib, urllib2, sys
- host = 'http://freecityid.market.alicloudapi.com'
- path = '/whapi/json/alicityweather/briefforecast3days'
- method = 'POST'
- appcode = '你自己的AppCode'
- querys = ''
- bodys = {}
- url = host + path
- bodys['cityId'] = '''2'''
- bodys['token'] = '''677282c2f1b3d718152c4e25ed434bc4'''
- post_data = urllib.urlencode(bodys)
- request = urllib2.Request(url, post_data)
- request.add_header('Authorization', 'APPCODE ' + appcode)
- //根据API的要求,定义相对应的Content-Type
- request.add_header('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8')
- response = urllib2.urlopen(request)
- content = response.read()
- if (content):
- print(content)
复制代码
我把他改成python3的代码如下:
- import urllib.parse
- import urllib.request
- host = 'http://freecityid.market.alicloudapi.com'
- path = '/whapi/json/alicityweather/briefforecast3days'
- method = 'POST'
- appcode = '708efccf6eb5445fae08702f68c5695c'
- querys = ''
- bodys = {}
- url = host+path
- bodys['cityId'] = '2'
- bodys['token'] = ''
- post_data = urllib.parse.urlencode(bodys).encode('utf-8')
- request = urllib.request.Request(url, post_data)
- request.add_header('Authorization', 'APPCODE' + appcode)
- request.add_header('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8')
- response = urllib.request.urlopen(request)
- content = response.read()
- if content:
- print(content)
复制代码
出现了以下错误:
- Traceback (most recent call last):
- File "D:/Python/weather/tq.py", line 20, in <module>
- response = urllib.request.urlopen(request)
- File "D:\Python\lib\urllib\request.py", line 222, in urlopen
- return opener.open(url, data, timeout)
- File "D:\Python\lib\urllib\request.py", line 531, in open
- response = meth(req, response)
- File "D:\Python\lib\urllib\request.py", line 641, in http_response
- 'http', request, response, code, msg, hdrs)
- File "D:\Python\lib\urllib\request.py", line 569, in error
- return self._call_chain(*args)
- File "D:\Python\lib\urllib\request.py", line 503, in _call_chain
- result = func(*args)
- File "D:\Python\lib\urllib\request.py", line 649, in http_error_default
- raise HTTPError(req.full_url, code, msg, hdrs, fp)
- urllib.error.HTTPError: HTTP Error 401: Unauthorized
复制代码 |
|