The*_*NTS 3 python rest basic-authentication
我正在尝试使用 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)
Run Code Online (Sandbox Code Playgroud)
在 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"}]'
Run Code Online (Sandbox Code Playgroud)
我认为您不想将dump列表转换为字符串。requests将把 python 数据结构打入正确的有效负载中。如果您指定关键字参数,该requests库也足够智能,可以生成正确的标头json。
你可以试试:
r = requests.post(url, auth=('username','password'), json=payload)
Run Code Online (Sandbox Code Playgroud)
此外,有时站点会阻止未知的用户代理。您可以尝试通过执行以下操作来假装自己是浏览器:
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)
Run Code Online (Sandbox Code Playgroud)
HTH。
| 归档时间: |
|
| 查看次数: |
16977 次 |
| 最近记录: |