Python向API发送请求

标签 python json api python-requests

这可能是一个简单的问题,但我找不到为什么我无法对 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/

相关文章:

python - 将 .htm 或 .html 扩展名与 python RE 匹配

java - 如何在Java中使用ElasticSearch JSON DSL?

python - 当我使用os.environ时,Django忽略DEBUG值,为什么?

java - 如何在 ListView 中显示??(使用okhttp库)

c++ - 如何使用 CLANG 作为解析器并使用 Python 作为脚本语言来解析 C++ 代码中的宏?

C# CURL POST(内容类型,哈希键)

python - 在两个子图之间共享 Tensorflow 中的权重

javascript - 在 for 循环中在对象中添加 +1 键

python - 值错误 : Mixing dicts with non-Series may lead to ambiguous ordering

javascript - 从网站发布推文