Search code examples
pythonpostcustom-action

Python: Send a POST request using just a raw string


I want to send a POST request using just a raw string.

I'm writing a parser. I've loaded page and seen such a complicated request with many headers and body in firebug:

__EVENTTARGET=&__EVENTARGUMENT=&__VIEW.... (11Kb or unreadable text)

How can I send this exact request one more time (headers+post body) manually (passing it as a huge string)?

Like:

func("%(headers) \n \n %(body)" % ... )

I want it to be send by my script (and response to be handled) and don't want to make a dictionary of parameters and headers manually.

Thank you.


Solution

  • The other answer just got too big and confusing and was showing more than what you are asking. I felt I should include a more concise answer for future readers to come across:

    import urllib2
    import urllib
    import urlparse
    
    # this was the header and data strings you already had
    headers = 'baz=3&foo=1&bar=2'
    data = 'baz=3&foo=1&bar=2'
    
    header_dict = dict(urlparse.parse_qsl(headers))
    
    r = urllib2.Request('http://www.foo.com', data, headers)
    resp = urllib2.urlopen(r)
    

    You will need to at least parse the headers back into a dict, but its minimal work. Then just pass it all along to a new request.

    *Note: This concise example assumes both your headers and your data body are application/x-www-form-urlencoded format. If the headers are in a raw string format like Key: Value, then see the other answer for more detail on parsing that first.

    Ultimately, you can't just copy-paste the raw text and run a new request. It has to be divided into header and data in the proper formats.