Python 连接到 HTTP 服务器
Python connecting to an HTTP server
在我的程序中,我正在尝试访问 https://api.dropbox.com/1/oauth2/token
。为此,我尝试使用 http.client.HTTPSConnection()
。但是,我从服务器收到了 400 语句,即使当我通过浏览器发送相同的请求时,我得到了实际响应:
{"error": "Call requires one of the following methods: POST, OPTIONS. Got GET."}
我相信子域会发生这种情况,因为我也测试了 https://docs.python.org/3/
的功能,结果非常相似。
这是我的代码 (Python3):
conn = http.client.HTTPSConnection('docs.python.org')
conn.request('get', '/3/')
response = conn.getresponse().read()
print(response)
我应该如何使用 http.client
库来发送正确的请求?
TL;DR:将小写字母 'get' 更改为大写字母 'GET' 应该可以解决问题。
原因:根据5.1.1节,RFC2616:
The Method token indicates the method to be performed on the
resource identified by the Request-URI. The method is case-sensitive.
RFC2616还定义了8个方法,分别是"OPTIONS"、"GET"、"HEAD"、"POST"、"PUT"、"DELETE"、"TRACE",和 "CONNECT"。都是大写的。
我们确实知道一些 HTTP 客户端,如 python-requests
和 jQuery.ajax
也支持小写方法,但它们不是 RFC 定义的使用这些方法的标准方式。为防止出现问题,请先使用大写字母。
在我的程序中,我正在尝试访问 https://api.dropbox.com/1/oauth2/token
。为此,我尝试使用 http.client.HTTPSConnection()
。但是,我从服务器收到了 400 语句,即使当我通过浏览器发送相同的请求时,我得到了实际响应:
{"error": "Call requires one of the following methods: POST, OPTIONS. Got GET."}
我相信子域会发生这种情况,因为我也测试了 https://docs.python.org/3/
的功能,结果非常相似。
这是我的代码 (Python3):
conn = http.client.HTTPSConnection('docs.python.org')
conn.request('get', '/3/')
response = conn.getresponse().read()
print(response)
我应该如何使用 http.client
库来发送正确的请求?
TL;DR:将小写字母 'get' 更改为大写字母 'GET' 应该可以解决问题。
原因:根据5.1.1节,RFC2616:
The Method token indicates the method to be performed on the resource identified by the Request-URI. The method is case-sensitive.
RFC2616还定义了8个方法,分别是"OPTIONS"、"GET"、"HEAD"、"POST"、"PUT"、"DELETE"、"TRACE",和 "CONNECT"。都是大写的。
我们确实知道一些 HTTP 客户端,如 python-requests
和 jQuery.ajax
也支持小写方法,但它们不是 RFC 定义的使用这些方法的标准方式。为防止出现问题,请先使用大写字母。