我正在尝试从python使用Google的QPX Express API。我在发送请求时不断遇到两个问题。起初我尝试的是:
url = "https://www.googleapis.com/qpxExpress/v1/trips/search?key=MY_KEY_HERE"
values = {"request": {"passengers": {"kind": "qpxexpress#passengerCounts", "adultCount": 1}, "slice": [{"kind": "qpxexpress#sliceInput", "origin": "RDU", "destination": location, "date": dateGo}]}}
data = json.dumps(values)
req = urllib2.Request(url, data, {'Content-Type': 'application/json'})
f = urllib2.urlopen(req)
response = f.read()
f.close()
print(response)
基于以下代码:urllib2和json
当我运行上面的代码时,我得到以下错误消息:
TypeError: POST data should be bytes or an iterable of bytes. It cannot be of type str.
我搜索了一个解决方案,并根据以下问题调整了我的代码:TypeError:POST数据应该是字节或可迭代的字节。它不能是str
我把我的代码改成了这个:
url = "https://www.googleapis.com/qpxExpress/v1/trips/search?key=AIzaSyCMp2ZnKI3J91sog7a7m7-Hzcn402FyUZo"
values = {"request": {"passengers": {"kind": "qpxexpress#passengerCounts", "adultCount": 1}, "slice": [{"kind": "qpxexpress#sliceInput", "origin": "RDU", "destination": location, "date": dateGo}]}}
data = json.dumps(values)
data = data.encode("utf-8")
req = urllib2.Request(url, data, {'Content-Type': 'application/json'})
f = urllib2.urlopen(req)
response = f.read()
f.close()
print(response)
然而,当我运行此代码时,我会收到以下错误消息:
urllib.error.HTTPError: HTTP Error 400: Bad Request
我也试着把utf-8改成ascii,但没有成功。我怎样才能让它正常工作?
这里有一个使用excellent请求库的解决方案。
import json
import requests
api_key = "YOUR API KEY HERE"
url = "https://www.googleapis.com/qpxExpress/v1/trips/search?key=" + api_key
headers = {'content-type': 'application/json'}
params = {
"request": {
"slice": [
{
"origin": "TXL",
"destination": "LIM",
"date": "2015-01-19"
}
],
"passengers": {
"adultCount": 1
},
"solutions": 2,
"refundable": False
}
}
response = requests.post(url, data=json.dumps(params), headers=headers)
data = response.json()
print data
我不知道为什么你的请求不起作用。也许真的是请求参数出错了。日期肯定需要在未来!
False在JSON中需要小写,因此您需要在Python中引用它,如"refundable" : "false"
。否则,您的查询看起来不错(显然您需要更新日期)。顺便说一下,在公共论坛中包含API密钥不是一个好的做法。