使用python调用阿里云天气API,失败了……
原本有urllib2的库,但是不能正常导入,故找到原因说可以用urllib3代替。
转向urllib3的时候,发现urllib3.request并不能正常使用。
看到有说request库需要单独使用,import urllib.request
import urllib, urllib3, sys
import ssl
import urllib.request
host = 'https://ali-weather.showapi.com'
path = '/ip-to-weather'
method = 'GET'
appcode = '你自己的AppCode'
querys = 'ip=223.5.5.5&need3HourForcast=0&needAlarm=0&needHourData=0&needIndex=0&needMoreDay=0'
bodys = {}
url = host + path + '?' + querys
request = urllib.request.Request(url)
request.add_header('Authorization', 'APPCODE ' + appcode)
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
response = urllib.request.urlopen(request, context=ctx)
content = response.read()
if (content):
print(content)
原有的阿里云给的示例为:
import urllib, urllib2, sys
import ssl
host = 'https://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')
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
response = urllib2.urlopen(request, context=ctx)
content = response.read()
if (content):
print(content)
阿里云API地址为“https://market.aliyun.com/products/57096001/cmapi023656.html?spm=5176.2020520132.101.2.52127218Fbtlrx#sku=yuncode1765600000”