简体   繁体   中英

urllib3 how to find code and message of Http error

I am catching http errors using python, but I want to know the code of the error (eg 400, 403,..). Additionally I want to get the message of the error. However, I can't find those two attributes in the documentation. Can anyone help? Thank you.

    try:
        """some code here"""
    except urllib3.exceptions.HTTPError as error:
        """code based on error message and code"""

Assuming that you mean the description of the HTTP response when you said "the message of the error", you can use responses from http.client as in the following example:

import urllib3
from http.client import responses

http = urllib3.PoolManager()
request = http.request('GET', 'http://google.com')

http_status = request.status
http_status_description = responses[http_status]

print(http_status)
print(http_status_description)

...which when executed will give you:

200
OK

on my example.

I hope it helps. Regards.

The following sample code illustrates status code of the response and cause of the error:

import urllib3
try:
  url ='http://httpbin.org/get'
  http = urllib3.PoolManager()
  response=http.request('GET', url)
  print(response.status)
except urllib3.exceptions.HTTPError as e:
  print('Request failed:', e.reason)

Status codes come from the response, while HTTPError means urllib3 cannot get the response. Status codes 400+ will not trigger any exception from urllib3.

Why are you catching it as exception? You want to see the http response, so you don't need to deal with it as an exception.

You could simply make your HTTP request and read response like this:

import urllib3
http = urllib3.PoolManager()
req = http.request('GET', 'http://httpbin.org/robots.txt')
status_code = req.status
server_response = req.data

Check urllib3 readthedocs for more info.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM