Tinku
Tinku

Reputation: 51

HTTP response not being manipulated

I made a HTTP request with the following line.

h.request('POST', uri, body,headers={})

I am collecting the response in a variable.

res = h.getresponse()

after that I am trying to print the response by

 print(res.msg)
 print(res.status)
 print(res.read())

After the 3 print statment I am trying to modify the response by storing the res.read() output in a different variable to convert to a string and to do further processing.

  text=res.read().decode("utf-8")  

But while doing so the decoded response is not getting stored in the variable. If I do a print on text after print(res.read()) it gives me nothing

 print(res.read())
 text=res.read().decode("utf-8")
 print(text)

The output of the above just prints me the first print statement. If I remove the first statement and do the following.

  text=res.read().decode("utf-8")
  print(text)

It gives me the required O/P. But I wanted both of them to work. So, is there a way to do so.

Upvotes: 0

Views: 28

Answers (2)

ThunderStorm
ThunderStorm

Reputation: 46

Or u can try following way.

from  requests import request
res = request('POST', uri, data,headers={})
print(res.text)

Upvotes: 0

Sazzy
Sazzy

Reputation: 1994

If you do res.read(), it reads the content of the response during the print statement. On the second execution you cannot read again, unless you seek back or re-do the request.

Store the first .read() in a variable, then print it.

Upvotes: 1

Related Questions