gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 07:59:15 26 4
gpt4 key购买 nike

我正在尝试使用 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

关于python - 如何使用 Python 2.7 发送 HTTP POST,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43377654/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com