Tags
python
Asked 2 years ago
11 Aug 2021
Views 279
Lila

Lila posted

From HTTPResponse to str in Python 3.6

From HTTPResponse to str in Python 3.6
lain

lain
answered May 1 '23 00:00

To convert an HTTPResponse object to a string by reading the response content and decoding it to a string using the decode() method . Here's an example:


import urllib.request

# Make a request
response = urllib.request.urlopen('https://www.example.com')

# Read the response content
response_data = response.read()

# Decode the response content to a string
response_string = response_data.decode('utf-8')

print(response_string)

In this example, we make a request to the URL https://www.example.com. The response is stored in the response variable as an HTTPResponse object. We then read the response content using the read() method and store it in the response_data variable as a bytes object. Finally, we decode the bytes object to a string using the decode() method with the encoding utf-8 and store it in the response_string variable.

The resulting response_string variable contains the response content as a string, which can be printed or used in other ways.
Post Answer