Kryštof Hilar
Kryštof Hilar

Reputation: 639

How to dump http request in python

I am using http in my application.

request = urllib2.Request(url, postdata) 

Is possible to get dump of this request on client side (after this line) ?

I need exactly what is sent to server (TCP dump ?), so

POST url HTTP/version\r\nHeaderKey: HeaderValue\r\n....

Upvotes: 4

Views: 3140

Answers (1)

Corey Goldberg
Corey Goldberg

Reputation: 60604

Is possible to get dump of this request on client side (after this line) ? I need exactly what is sent to server (TCP dump ?)

you are looking for a log at the tcp layer, but you haven't actually sent anything over the wire via tcp?

All you did was create a Request object.

If you were to send the request you created, you could enable debug in a handler and view headers/data both sent and received:

import httplib
import urllib
import urllib2

url = 'http://example.com'
headers = {'HeaderKey': 'HeaderValue'}
data = urllib.urlencode({})
request = urllib2.Request(url, headers=headers, data=data)
handler = urllib2.HTTPHandler()
handler.set_http_debuglevel(1)
opener = urllib2.build_opener(handler)
response = opener.open(request)
response.read()
response.close()

ouput:

send: 'POST / HTTP/1.1\r\nAccept-Encoding: identity\r\nContent-Length: 0\r\nHost: example.com\r\nUser-Agent: Python-urllib/2.7\r\nConnection: close\r\nContent-Type: application/x-www-form-urlencoded\r\nHeaderkey: HeaderValue\r\n\r\n'
reply: 'HTTP/1.1 200 OK\r\n'
[snip]

Upvotes: 2

Related Questions