2017-04-12 35 views
0

我试图使用Python发送HTTP POST请求。我可以使用3.0来工作,但我无法在2.7上找到一个好例子。如何使用Python 2.7发送HTTP POST POST

hdr = {"content-type": "application/json"} 
payload= ("<html><body><h1>Sorry it's not Friday yet</h1> </body></html>") 
r = requests.post("http://my-url/api/Html", 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) 

的API采用以下格式的JSON:

{ 
    HTML : "a html string" 
} 

,并在此格式返回一个JSON:

{ 
    BinaryData: 'base64 encoded string'  
} 

回答

0

在Python 2.x的,应该是这样的

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