Python向API发送Post请求

4
这可能是一个简单的问题,但我找不到原因为什么我无法调用API网址的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)得到了返回值

<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没问题,但当我使用requests/json python时出现了问题……我想我可能漏掉了某些东西,我无法检测到。请帮忙指点正确的方向。谢谢。


response.text 包含什么内容? - Abdul Niyas P M
它什么也不给,只是一个空白行... - chenoi
1个回答

8

我遇到了类似的错误,将数据转储解决了这个问题。尝试将请求体作为转储传递:


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

1
是的...现在它可以工作了...但为什么需要转储正文数据呢?我之前使用过类似的API并且使用相同的方法...但这次却不行...当转储数据时...问题得到了解决。不知道为什么,先生? - chenoi
Python字典如何作为数据发送到API并且API希望的是什么格式。转储将强制字典以保证套接字传输安全的方式转换为字节。 - Prayson W. Daniel

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接