简体   繁体   中英

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 -

Input using "head":

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

Output:

<Response [301]>

While input using "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?

How get and head works differently to produce these two different results?

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.

requests.get() follows redirects automatically for your convenience.

Switch that off if you don't want this behavior.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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