这可能是一个简单的问题,但我找不到为什么我无法对 api url 调用 post 请求的问题。我交叉检查了类似的问题,但我的仍然有问题。
这是脚本
import requests
import json
#API details
url = "http://192.168.1.100:9792/api/scan"
body = {"service":"scan", "user_id":"1", "action":"read_all", "code":"0"}
headers = {'Content-Type': 'application/json'}
#Making http post request
response = requests.post(url, headers=headers, data=body, verify=False)
print(response)
#Decode response.json() method to a python dictionary for data process utilization
dictData = response.json()
print(dictData)
with open('scan.json', 'w') as fp:
json.dump(dictData, fp, indent=4, sort_keys=True)
出现错误
raise ValueError("No JSON object could be decoded")
ValueError: No JSON object could be decoded
打印(响应)得到返回
<Response [200]>
如果我像下面那样运行curl,那么它将返回来自api post请求的数据
curl --header "Content-Type: application/json" --request POST --data '{"service":"scan","user_id":"1","action":"read_all","code":"0"}' http://192.168.1.100:9792/api/scan
使用curl ok...但是当我使用requests/json python 时出现问题...我想我可能会错过一些我无法检测到的东西。请帮助并指出我正确的方法。谢谢。
最佳答案
我遇到了类似的错误,转储我的数据解决了这个问题。尝试将你的 body 作为垃圾场传递:
import requests
import json
#API details
url = "http://192.168.1.100:9792/api/scan"
body = json.dumps({"service":"scan", "user_id":"1", "action":"read_all", "code":"0"})
headers = {'Content-Type': 'application/json'}
#Making http post request
response = requests.post(url, headers=headers, data=body, verify=False)
print(response.json())
关于Python向API发送请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58796540/