5

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.

Arnb
  • 977
  • 1
  • 7
  • 11

2 Answers2

8

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)
Tomalak
  • 332,285
  • 67
  • 532
  • 628
0

Similarly to Tomalak's answer, to get a 200 instead of a 301 from a requests.head call to a redirect, set allow_redirects=True:

resp = requests.head("http://stackoverflow.com", allow_redirects=True)

If allow_redirects is not provided, it will be set to False (as opposed to the default request behavior).

https://requests.readthedocs.io/en/latest/api/#requests.head

JamesParrott
  • 91
  • 1
  • 3