Search code examples
pythonhttpgetpython-requests

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.


Solution

  • 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)