python httplib for http debugging

In http debugging, it's useful to send a http request as exactly as you want, to pinpoint certain problem. I encountered these problems in a recent debugging session.

  • how can I send a http 1.0 request?
  • how to send a specific header?
  • how to control the order of headers?

A simple python script can make it happen.

Send old HTTP1.0 request


    from http.client import HTTPConnection
    HTTPConnection._http_vsn = 10
    HTTPConnection._http_vsn_str = 'HTTP/1.0'

Display request response info


    conn = HTTPConnection('10.10.0.1', 80)
    conn.set_debuglevel(level=1) 

Keep a serials of headers in order

    from collections import OrderedDict
    headers = OrderedDict([
        ('X-Source-Id', '10.0.0.1'),
        ('X-Up-Bear-Type', 'CDMA'),
        ('Host', 'www.qq.com'),
        ('X-Hts_user', 'true'),
        ('X-Forwarded-For', '192.168.2.204'),
        ('Accept', '*/*'),
        ('User-Agent', 'Wget/1.11.4 Red Hat modified')
    ])

    conn.request("GET", "/create_iphone/create.html", headers=headers)
    r = conn.getresponse()

    if r1.status != 200:
        print(r1.read())

    conn.close()