我正在尝试发送POST
请求。对于此请求,我想在正文中发送JSON
,但此操作不起作用,并且显示错误消息:can't concat str to bytes
。提交具有POST
正文的JSON
请求的正确方法是什么?
import http.client, urllib.parse
def update_status(status, versionId):
conn = http.client.HTTPConnection(server_ip, server_port)
body = {
"status": status,
"id": versionId
}
print("body:", body)
headers = {"Content-type": "application/json"}
conn.request("POST", "", body, headers)
response = conn.getresponse()
print("response status:", response.status)
print("response reason:", response.reason)
return response
return update_status
答案 0 :(得分:1)
考虑使用请求模块。如下所示:
import requests
body = {"key": "value"}
response = requests.post("http://<SOME_URL>", json=body)
答案 1 :(得分:1)
您需要先序列化数据。
data = json.dumps(body)
data = data.encode('utf8')
conn.request("POST", "", data, headers)