2017-04-12 34 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