6

Preferably using the requests library

HTTP/1.1 200 OK        <-- I want this...
Content-Type: text/html; charset=utf-8

That property doesn't seem to be provided http://docs.python-requests.org/en/master/api/#requests.Response

Is there a way to access the raw response string?

I found http://docs.python-requests.org/en/master/user/quickstart/#raw-response-content but I'm not seeing any content

r = requests.head(uri, stream=True)
print(r.raw.read(10)) # -> b''

2 Answers 2

18

I think what you want is this. Calling version on raw will give you HTTP version. (I found the example of server running HTTP 1.0 using Shodan for testing purposes)

>>> import requests
>>> response = requests.get("http://104.71.136.252/", timeout=60, verify=False)
>>> response.raw.version
10
>>> response = requests.get("http://stackoverflow.com", timeout=60, verify=False)
>>> response.raw.version
11

This is not mentioned in the docs directly, I found it by using PyCharm's autocomplete feature. But I have looked into it. The reason why is HTTP version returned as integer is historical.

Requests for python3 uses urllib3. Urllib3's class urllib3.response.HTTPResponse is backwards compatible with httplib’s HTTPResponse see urllib3 docs

Now if it's backwards compatible you have to check documentation for httplib and if you search you'll find

HTTP protocol version used by server. 10 for HTTP/1.0, 11 for HTTP/1.1.

Here is the exact link HTTPResponse.version

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks! It seems to be exactly what I want but why is the version returned as an int? I'm trying to find it in the source code but can't figure out where.
Can I assume that HTTP/2.0 will return 20? I tried http2.golang.org and it returns 11. Live headers says that the server is returning HTTP/2.0 OK. I just realized that my example shows a request... Sorry about that.
I don't think it's as straightforward as returning 20 with HTTP 2.0. Check the RFC tools.ietf.org/html/rfc7540#section-3.2
-2

request.raw.version_string gives the text presentation, e.g. HTTP/1.1.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.