Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get HTTP status message in (py)curl?

Tags:

spending some time studying pycurl and libcurl documentation, i still can't find a (simple) way, how to get HTTP status message (reason-phrase) in pycurl.

status code is easy:

import pycurl import cStringIO  curl = pycurl.Curl() buff = cStringIO.StringIO() curl.setopt(pycurl.URL, 'http://example.org') curl.setopt(pycurl.WRITEFUNCTION, buff.write) curl.perform()  print "status code: %s" % curl.getinfo(pycurl.HTTP_CODE) # -> 200  # print "status message: %s" % ??? # -> "OK" 
like image 446
mykhal Avatar asked Apr 27 '10 18:04

mykhal


People also ask

How do I get my HTTP status code on curl?

Append a line "http_code:200" at the end, and then grep for the keyword "http_code:" and extract the response code. In this case, you can still use the non-silent mode / verbose mode to get more information about the request such as the curl response body. Save this answer. Show activity on this post.

How do I see curl response?

Display only Response Headers in curl If you want to display only the response headers, you can use the --head flag. Note: -s hides the progress bar. -D - dump headers to stdout indicated by -


2 Answers

i've found a solution myself, which does what i need, but could be more robust (works for HTTP).

it's based on a fact that captured headers obtained by pycurl.HEADERFUNCTION include the status line.

import pycurl import cStringIO import re  curl = pycurl.Curl()  buff = cStringIO.StringIO() hdr = cStringIO.StringIO()  curl.setopt(pycurl.URL, 'http://example.org') curl.setopt(pycurl.WRITEFUNCTION, buff.write) curl.setopt(pycurl.HEADERFUNCTION, hdr.write) curl.perform()  print "status code: %s" % curl.getinfo(pycurl.HTTP_CODE) # -> 200  status_line = hdr.getvalue().splitlines()[0] m = re.match(r'HTTP\/\S*\s*\d+\s*(.*?)\s*$', status_line) if m:     status_message = m.groups(1) else:     status_message = ''  print "status message: %s" % status_message # -> "OK" 
like image 102
mykhal Avatar answered Oct 02 '22 09:10

mykhal


This is an old thread but I got here looking for similar information. If it is just the status code you're looking for, such as 200, 404, 500 etc. then just do:

your_curl_handle.getinfo(pycurl.RESPONSE_CODE)

which should return a numerical status code :)

like image 30
Kalabaaz Avatar answered Oct 02 '22 11:10

Kalabaaz