2017-04-12 14 views
0

私はPythonでHTTP POSTリクエストを送信しようとしています。私はそれを3.0で動作させることができますが、私は2.7で良い例を見つけることができませんでした。プロパティはPython 2.7でHTTP 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 
関連する問題