gpt4 book ai didi

python - 在 Python 中将数据发布到 api 时无法将 str 连接到字节错误

转载 作者:可可西里 更新时间:2023-11-01 17:16:24 26 4
gpt4 key购买 nike

我发布的 api url 如下:

https://az-us-eu-dev-sgtps-apilayer.azurewebsites.net/api/HttpTrigger1?code=sqEdwsf6vapdcPnI9zxwlwXHw==

我正在向它发布 json 数据,我得到了代码 200 的正确响应。

我必须从 python 做同样的事情,我使用下面的代码:

headers = {'Content-Type': 'application/json'}

conn = http.client.HTTPSConnection('az-us-eu-dev-sgtps-apilayer.azurewebsites.net')

conn.request("POST", "/api/HttpTrigger1?code=sqEdwsf6vapdcPnI9zxwlwXHw==", jdata, headers)
response = conn.getresponse()
rdata = response.read()
rdata = rdata.decode('utf8')
rdata = json.loads(rdata)

但是在上面的第 3 行,我遇到了以下错误:

can't concat str to bytes

我试过这样做:

url = "/api/HttpTrigger1?code=sqEdwsf6vapdcPnI9zxwlwXHw=="
new_url = str.encode(url)
conn.request("POST", new_url, jdata, headers)

下面是 jdata 是要发布到 api url 的 json 数据:

{
"reqType": "True",
"date": "27-09-2019"
}

但它显示相同的错误。我该如何解决?

最佳答案

您可以使用 requests类似模块,

>>> import requests
>>> import json
>>> endpoint = 'https://az-us-eu-dev-sgtps-apilayer.azurewebsites.net/api/HttpTrigger1?code=sqEdwsf6vapdcPnI9zxwlwXHw=='
>>> jdata = {"reqType": "True", "date": "27-09-2019"}
>>> headers = {'Content-Type': 'application/json'}
>>> r = requests.post(endpoint, data=json.dumps(jdata), headers=headers)

Instead of encoding the dict yourself, you can also pass it directly using the json parameter (added in version 2.4.2) and it will be encoded automatically:

>>> r = requests.post(endpoint, json=jdata, headers=headers)
>>> r.json() # for response

关于python - 在 Python 中将数据发布到 api 时无法将 str 连接到字节错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58282617/

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