如何使用JSON正文发送POST请求?

时间:2019-10-04 11:17:46

标签: python json http post

我正在尝试发送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

2 个答案:

答案 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)