Skip to main content
 首页 » 编程设计

python之如何使用 Python 2.7 发送 HTTP POST

2025年05月04日15myhome

我正在尝试使用 Python 发送 HTTP POST 请求。我可以让它在 3.0 上工作,但我找不到 2.7 上的好例子。

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'       
} 

请您参考如下方法:

在 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