首页 > 解决方案 > Python Post 请求到 API

问题描述

这可能是一个简单的问题,但我找不到为什么我无法将发布请求调用到 api url 的问题。我对类似的问题进行了交叉检查,但我的仍然有问题。

这是脚本

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 ok..它会从 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 时遇到问题...我想我可能会错过一些我无法检测到的东西。请帮助并指出正确的方法。谢谢你。

标签: pythonjsonapipython-requests

解决方案


我有类似的错误,转储我的数据解决了这个问题。尝试将您的身体作为垃圾场传递:


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())

推荐阅读