简体   繁体   English

Python请求标头显示“ 301”,而获取返回“ 200”

[英]Python requests head shows “301” while get returns “200”

While working with python requests library, I got two different responses using get and head http methods - 使用python请求库时,我使用get和head http方法得到了两个不同的响应-

Input using "head": 使用“ head”输入:

requests.head("http://stackoverflow.com")

Output: 输出:

<Response [301]>

While input using "get": 使用“ get”输入时:

requests.get("http://stackoverflow.com")

The output is: 输出为:

<Response [200]>

While this is quite obvious that " http://stackoverflow.com " redirects to " https://stackoverflow.com " (as requests.head("https://stackoverflow.com") returns <Response [200]> ), which explains the 301 response in the first instance, but why didn't it give the same response for "get" method? 尽管这很明显,“ http://stackoverflow.com ”重定向到“ https://stackoverflow.com ”(作为requests.head("https://stackoverflow.com")返回<Response [200]> ) ,它首先解释了301响应,但是为什么它不对“ get”方法给出相同的响应?

How get and head works differently to produce these two different results? get和head如何不同地产生这两种不同的结果?

I read the w3.org documentation and similar questions in stackoverflow (eg, HEAD request receives "403 forbidden" while GET "200 ok"? ) and other websites, but they don't address this particular difference. 我阅读了w3.org文档以及stackoverflow中的类似问题(例如HEAD请求收到“ 403禁止”,而GET获得“ 200 ok”? )和其他网站,但是它们没有解决这一特殊区别。

requests.get() follows redirects automatically for your convenience. requests.get()自动跟随重定向以方便您。

Switch that off if you don't want this behavior. 如果您不希望出现这种情况,请将其关闭。

resp = requests.get("http://stackoverflow.com", allow_redirects=False)
print(resp.status_code)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM