【问题标题】:Python Post request to APIPython Post 请求到 API
【发布时间】:2020-03-06 20:32:42
【问题描述】:

这可能是一个简单的问题,但我找不到为什么我无法将发布请求调用到 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 ok...但是当我使用 requests/json python 时遇到问题...我想我可能会错过一些我无法检测到的东西。请帮助并指出正确的方法。谢谢。

【问题讨论】:

  • response.text 包含什么?
  • 它什么也没给,只是空行...

标签: python json api python-requests


【解决方案1】:

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


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

【讨论】:

  • 是的……它现在可以工作了……但是为什么需要转储正文数据? ....我以前使用过类似的api并使用相同的方法...但是这次..不能...当转储数据时...解决了这个问题。先生知道为什么吗?
  • 它如何将 Python 字典作为数据发送到您的 API 以及 API 期望的格式。转储以确保套接字传输安全的方式强制字典转换为字节
猜你喜欢
  • 2019-12-28
  • 2018-10-29
  • 1970-01-01
  • 1970-01-01
  • 2018-07-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多