user1267259
user1267259

Reputation: 801

Python 3.x how to get http version (using requests library)

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''

Upvotes: 6

Views: 10165

Answers (1)

J91321
J91321

Reputation: 727

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

Upvotes: 18

Related Questions