How to Retrieve the Response Code of an HTTP Request in Python using the http.client Module



Python


In this article, we show how to retrieve the response code of an HTTP request in Python using the http.client module.

The http.client module is a module that uses the HTTP protocol to achieve different tasks.

The HTTP protocol is how servers on the internet communicate with each other so that information such as web pages on the web can be retrieved.

In this article, we show how to retrieve the response code of an HTTP request. The response code is if the server was able to successfully serve the page that is requested. A successful response is 200. A server error is 500. A client error is 400, with a Page Not Found error being a 404 error. There are many other types of codes. For a full list of these codes, you can visit this link: HTTP response status codes.

So, in this example, we will do a GET request that retrieves the content of this website's home page.

Using the following code below, we are able to do this.



Let's now go over this code.

First, we import the http.client module, so that we can use its functionality.

We then create a variable, h, which stores the connection to the server that hosts the website, www.learningaboutelectronics.com, specifically the home page, in this case. If we wanted to access another page, we specify the path to that page. In this case, we are simply going to retrieve the content on the home page of the website.

On this variable, h, we perform a GET request, which allows us to retrieve information from this web page.

We then create a variable, data, which allows us to get basically all the data that is on the home page of www.learningaboutelectronics.com

We retrieve all contents of the page and store it in this variable, data

data.code is the response that is returned by the server for this request that is made. Running this code, you should get an HTTP response of 200, which means that the request succeeded or was successful.

Below is the output from the code above.



So you see that we have a successful request response of 200.

So this is how we can retrieve the response code of an HTTP request in Python using the http.client module.


Related Resources

How to Draw a Rectangle in Python using OpenCV

How to Draw a Circle in Python using OpenCV

How to Draw a Line in Python using OpenCV

How to Add Text to an Image in Python using OpenCV

How to Display an OpenCV image in Python with Matplotlib

How to Use Callback functions to Connect Images to Events in Python using OpenCV

How to Check for Multiple Events in Python using OpenCV



HTML Comment Box is loading comments...