Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to view the HTTP headers, response code and html content using urllib3 in Python?

I am interested in retrieving the response code, body and HTTP headers using urllib3. The previous code which I had written was in Python 2 and now I have to rewrite it for Python 3.

import urllib3

http = urllib3.PoolManager();
response = http.request('GET', 'http://192.168.43.131:8000')
print(response)

I tried different sources, but can someone point me in the right direction of the give a few pointers?

like image 870
Mufa Sam Avatar asked Mar 10 '26 11:03

Mufa Sam


1 Answers

I think you mean this:

import json

import urllib3 # pip install urllib3

http = urllib3.PoolManager()
response = http.request('GET', 'http://192.168.43.131:8000')
print(response.status)
print(response.headers)
print(json.loads(response.data.decode('utf-8'))) # body

Convert body to json with orjson:

import orjson  # pip install orjson

import urllib3 # pip install urllib3

response = http.request('GET', 'http://192.168.43.131:8000')

print(orjson.loads(response.data)) # body

doc: https://urllib3.readthedocs.io/en/latest/user-guide.html

like image 83
omides248 Avatar answered Mar 13 '26 00:03

omides248



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!