Python连接到HTTP服务器 [英] Python connecting to an HTTP server

查看:579
本文介绍了Python连接到HTTP服务器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的计划中,我正在尝试访问 https://api.dropbox.com/1/oauth2/token 。为了做到这一点,我试图使用 http.client.HTTPSConnection()。但是,我收到了来自服务器的400声明,即使我通过浏览器发送相同的请求时,我得到了实际的回复:

In my program, I am trying to access https://api.dropbox.com/1/oauth2/token. In order to do that, I was trying to use http.client.HTTPSConnection(). However, I am receiving a 400 statement from the server, even though when I send the same request through my browser, I get an actual response:

{错误:调用需要以下方法之一:POST,OPTIONS。得到GET。}

我相信这个因为我还测试了 https://docs.python.org/3/ 的功能,结果非常相似。

I believe that this happens for subdomains, since I also tested the function for https://docs.python.org/3/, and the result is very similar.

这是我的代码(Python3):

Here is my code (Python3):

conn = http.client.HTTPSConnection('docs.python.org')
conn.request('get', '/3/')
response = conn.getresponse().read()
print(response)

我应该如何使用 http.client 库来发送正确的请求?

How should I use the http.client library to send the proper request?

推荐答案

TL; DR:将小写'get'更改为大写'GET'应解决问题。

TL;DR: Change the lowercase 'get' to uppercase 'GET' should resolve the problem.

原因:根据5.1.1节, RFC2616

The reason: according to section 5.1.1, RFC2616:


Method标记表示方法在Request-URI标识的
资源上执行。该方法区分大小写。

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。所有这些都是大写的。

RFC2616 also defined 8 methods which are "OPTIONS", "GET", "HEAD", "POST", "PUT", "DELETE", "TRACE", and "CONNECT". All of them are uppercase.

我们知道一些HTTP客户端,如 python-requests jQuery.ajax 也支持小写方法,但它们不是RFC为使用这些方法定义的标准方式。为防止出现问题,请先使用大写字母。

We do know some HTTP clients like python-requests and jQuery.ajax also support lowercase methods but they are just not the standard way defined by the RFC for using those methods. To prevent issues, use uppercase ones first.

这篇关于Python连接到HTTP服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆