python - Google QPX Express API 返回 HTTP 错误 403 : Forbidden - Python

标签 python python-3.x http google-api google-qpx-express-api

import json
import requests
import urllib

url = "https://developers.google.com/qpx-express/v1/trips/search?key=<API_key>"
headers = {'content-type': 'application/json'}

params = {
  "request": {
    "slice": [
      {
        "kind": "qpxexpress#sliceInput",
        "origin": "BOS",
        "destination": "SFO",
        "date": "2017-06-30"
      }
    ],
    "passengers": {
      "kind": "qpxexpress#passengerCounts",
      "adultCount": 1,
    },
    "refundable": "false",
    "solutions": 20,
  }
}

#jsonreq = json.dumps(params)

data = urllib.parse.urlencode(params)
binary_data = data.encode('utf-8')
req = urllib.request.Request(url, binary_data)
flight = urllib.request.urlopen(req)
response = flight.read()
print(response)

我正在尝试检索航类票价,但 Google API 一直给我 HTTP 错误 403:禁止访问。

我检查了我的开发者控制台,QPX Express API 已启用。此外,我还生成了一个没有限制的 API_key。

这里是错误:

HTTPError                                 Traceback (most recent call last)
<ipython-input-189-cc6dee70b145> in <module>()
     31 binary_data = data.encode('utf-8')
     32 req = urllib.request.Request(url, binary_data)
---> 33 flight = urllib.request.urlopen(req)
     34 response = flight.read()
     35 print(response)

C:\Anaconda3\lib\urllib\request.py in urlopen(url, data, timeout, cafile, capath, cadefault, context)
    161     else:
    162         opener = _opener
--> 163     return opener.open(url, data, timeout)
    164 
    165 def install_opener(opener):

C:\Anaconda3\lib\urllib\request.py in open(self, fullurl, data, timeout)
    470         for processor in self.process_response.get(protocol, []):
    471             meth = getattr(processor, meth_name)
--> 472             response = meth(req, response)
    473 
    474         return response

C:\Anaconda3\lib\urllib\request.py in http_response(self, request, response)
    580         if not (200 <= code < 300):
    581             response = self.parent.error(
--> 582                 'http', request, response, code, msg, hdrs)
    583 
    584         return response

C:\Anaconda3\lib\urllib\request.py in error(self, proto, *args)
    508         if http_err:
    509             args = (dict, 'default', 'http_error_default') + orig_args
--> 510             return self._call_chain(*args)
    511 
    512 # XXX probably also want an abstract factory that knows when it makes

C:\Anaconda3\lib\urllib\request.py in _call_chain(self, chain, kind, meth_name, *args)
    442         for handler in handlers:
    443             func = getattr(handler, meth_name)
--> 444             result = func(*args)
    445             if result is not None:
    446                 return result

C:\Anaconda3\lib\urllib\request.py in http_error_default(self, req, fp, code, msg, hdrs)
    588 class HTTPDefaultErrorHandler(BaseHandler):
    589     def http_error_default(self, req, fp, code, msg, hdrs):
--> 590         raise HTTPError(req.full_url, code, msg, hdrs, fp)
    591 
    592 class HTTPRedirectHandler(BaseHandler):

HTTPError: HTTP Error 403: Forbidden

最佳答案

您确定您使用的网址正确吗?我最初遇到了与您相同的问题,但发现下面的代码有效。我也在使用请求,这使得传递 JSON 更加直接。

import requests
url='https://www.googleapis.com/qpxExpress/v1/trips/search?key=%s'%google_api_key

params = {"request": {
     "slice": [{"kind": "qpxexpress#sliceInput",
                "origin": "BOS",
                "destination": "SFO",
                "date": "2017-06-30"}],
     "passengers": {"kind": "qpxexpress#passengerCounts",
               "adultCount": 1,},
     "refundable": "false",
     "solutions": 20,}
    }

requests.post(url, json=params, headers = {'content-type': 'application/json'})

关于python - Google QPX Express API 返回 HTTP 错误 403 : Forbidden - Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43162901/

相关文章:

Python time.time() 在并发程序中的可靠性

python - 我如何从 django 模型中提取元数据

python - 查找 Excel/CSV 文件的实际列引用 - Python Pandas

c++ - 使用 C++ 的简单 HTTP 请求

http - 使用 Wireshark 调试 HTTP/HTTPS

.net - 删除期望 : 100-continue from basicHttpBinding

python - 从另一个 DataFrame.describe() 创建 DataFrame - Pandas

python - python中的两种颜色热图

python - 如何获取函数参数类型?

python - 如何防止打印值时出现空格