How to Send a Http Post with Python 2.7

How to Send a Http Post with Python 2.7

I'm trying to send a HTTP POST request with Python. I can get it to work with 3.0, but I couldn't find a good example on 2.7.

hdr = {"content-type": "application/json"}
payload= ("<html><body><h1>Sorry it's not Friday yet</h1> </body></html>")
r = requests.post("", json={"HTML": payload})

with open ('c:/temp/a.pdf', 'wb') as f:
    b64str = json.loads(r.text)['BinaryData']  #base 64 string is in BinaryData attr
    binStr = binascii.a2b_base64(b64str)  #convert base64 string to binary
    f.write(binStr)

The api takes a json in this format:

{
  HTML : "a html string"
}

and returns a json in this format:

{
    BinaryData: 'base64 encoded string'      
}

2 Answers

In Python 2.x it should be like this

import json
import httplib

body =("<html><body><h1>Sorry it's not Friday yet</h1> </body></html>")
payload = {'HTML' : body}
hdr = {"content-type": "application/json"}

conn = httplib.HTTPConnection('my-url')
conn.request('POST', '/api/Html', json.dumps(payload), hdr)
response = conn.getresponse()
data = response.read() # same as r.text in 3.x

The standard way is with the urllib2 module

from urllib import urlencode
import urllib2
def http_post(url, data):
    post = urlencode(data)
    req = urllib2.Request(url, post)
    response = urllib2.urlopen(req)
    return response.read()
1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Sarah Jenkins
Author

Sarah Jenkins

Sarah Jenkins is a veteran tech journalist with over 12 years of experience covering artificial intelligence, mobile innovations, and digital ethics. Her insights have appeared in leading technology publications worldwide.