364,111 Members | 2066 Browsing Online
Community for Developers & IT Professionals
Bytes IT Community

HTTPResponse.read() returns an empty string?

Christoph Söllner
P: n/a
Christoph Söllner
Hi again,

my Source:
"""
import httplib
conn = httplib.HTTPConnection('www.python.org');
conn.request("GET", "/index.html");
answ = conn.getresponse();
print answ.status, answ.reason[color=blue][color=green][color=darkred]
>>> 200 OK[/color][/color][/color]
conn.close();
print "Start";[color=blue][color=green][color=darkred]
>>> Start[/color][/color][/color]
print answ.read();[color=blue][color=green][color=darkred]
>>>[/color][/color][/color]
print len(answ.read());[color=blue][color=green][color=darkred]
>>> 0[/color][/color][/color]
print "End";[color=blue][color=green][color=darkred]
>>> End[/color][/color][/color]

And the header states a content length of 11kBytes. What am I doin wrong?

Thanks again,
Chris


Oct 18 '05 #1
Share this Question
Share on Google+
2 Replies


Christoph Söllner
P: n/a
Christoph Söllner
ok got it:
One cannot close the connection before reading the answer.
Seems that in my original source the new assigned variable
'answ' is destroyed or emptied with the connection.close()
command; very strange behaviour.[color=blue]
> """
> import httplib
> conn = httplib.HTTPConnection('www.python.org');
> conn.request("GET", "/index.html");
> answ = conn.getresponse();
> print answ.status, answ.reason[color=green][color=darkred]
>>>> 200 OK[/color][/color]
> conn.close();
> print "Start";[color=green][color=darkred]
>>>> Start[/color][/color]
> print answ.read();[color=green][color=darkred]
>>>>[/color][/color]
> print len(answ.read());[color=green][color=darkred]
>>>> 0[/color][/color][/color]


Oct 18 '05 #2

Marc 'BlackJack' Rintsch
P: n/a
Marc 'BlackJack' Rintsch
In <dj2m7k$s7n$1@wsc10.lrz-muenchen.de>, Christoph Söllner wrote:
[color=blue]
> ok got it:
> One cannot close the connection before reading the answer.[/color]

Yep, because the "answer" is read over the connection.
[color=blue]
> Seems that in my original source the new assigned variable
> 'answ' is destroyed or emptied with the connection.close()
> command; very strange behaviour.[/color]

No, it's not emptied or destroyed. The read() method reads the content
over the connection. That doesn't work if the connection is closed. It's
like closing a file and then reading from it.

The response object contains just the headers. So you can inspect them
before you decide to download the actual content.

Ciao,
Marc 'BlackJack' Rintsch
Oct 18 '05 #3

Post your reply

Help answer this question



Didn't find the answer to your Python question?

You can also browse similar questions: Python