gpt4 book ai didi

具有基本身份验证的 Python REST POST

转载 作者:行者123 更新时间:2023-12-02 20:15:36 25 4
gpt4 key购买 nike

我正在尝试使用 Python 3 获取 POST 请求,该请求将向使用基本身份验证的平台提交 json 有效负载。我收到 405 状态错误,并认为这可能是由于我的负载格式造成的。我正在学习Python,但仍然不确定何时使用“与”、对象与数组以及某些请求的语法。搜索时,我无法找到使用基本身份验证发布数组的类似问题。以下是我现在有:

import requests
import json

url = 'https://sampleurl.com'
payload = [{'value': '100','utcRectime': '09/23/2018 11:59:00 PM','comment': "test",'correctionValue': '0.0','unit': 'C'}]
headers = {'content-type': 'application/json'}

r = requests.post(url, auth=('username','password'), data=json.dumps(payload), headers=headers)


print (r)

在 API swagger 中测试,CURL 包含以下格式:

curl -X POST --header 'Content-Type: application/json' --header 'Accept: application/json' -d '[{"value": "100","utcRectime": "9/23/2018 11:59:00 PM","comment": "test","correctionValue": "0.0","unit": "C"}]' 

最佳答案

我认为您不想将列表转储到字符串中。 requests 会将 python 数据结构打入正确的有效负载中。如果您指定 json 关键字参数,requests 库也足够智能,可以生成正确的 header 。

你可以尝试:

r = requests.post(url, auth=('username','password'), json=payload)

此外,有时网站会阻止未知的用户代理。您可以尝试通过执行以下操作来假装自己是浏览器:

headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'}
r = requests.post(url, auth=('username','password'), json=payload, headers=headers)

HTH。

关于具有基本身份验证的 Python REST POST,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52469747/

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