Python对API的Post请求

2024-10-03 00:22:22 发布

您现在位置:Python中文网/ 问答频道 /正文

这可能是一个简单的问题,但我找不到为什么我不能调用post请求到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,它将从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时遇到了问题…我想我可能错过了一些我无法检测到的东西。请帮我指一下正确的路。非常感谢。你知道吗


Tags: importapijsonhttpurldatascanresponse
1条回答
网友
1楼 · 发布于 2024-10-03 00:22:22

我也有类似的错误,我的数据解决了这个问题。试着把你的身体当作垃圾桶:


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

相关问题 更多 >