tags:

views:

60

answers:

2

I know how to do this with httplib, but I need to also set the user-agent and I'm sure you need urllib to do that. How can I get the http response codes with urllib?

+4  A: 

You can use .getcode() in urllib2 to get the HTTP code:

urllib2.urlopen("http://google.com").getcode()

Full headers with are in info() as a list:

urllib2.urlopen("http://google.com").info().headers
carl
>>> urllib2.urlopen("http://google.com").info().getcode()Traceback (most recent call last): File "<pyshell#43>", line 1, in <module> urllib2.urlopen("http://google.com").info().getcode()AttributeError: HTTPMessage instance has no attribute 'getcode'
d-c
@carl: I think the first line of code should be `urllib2.urlopen("http://google.com").getcode()`
Manoj Govindan
@Manoj Govindan, thanks
carl
A: 

Actually, httplib DOES allow to set User-Agent.

headers = { 'User-Agent' : 'someapp', 'Content-Type' : 'text/html' }  
conn = httplib.HTTPConnection(host, port)  
conn.request('POST', '/foobar', 'mydata', headers)
blaze