gpt4 book ai didi

python - 如何将http请求转换为Python?

转载 作者:太空宇宙 更新时间:2023-11-03 19:52:24 24 4
gpt4 key购买 nike

我需要你的帮助。

我希望与端口号 3 上包含传感器数据的 REST API 进行通信。我有一个 Json (POST) 请求,可以在 Insomnia 等 REST 客户端上完美执行。

我的要求:

{ "header": { "portNumber": 3 }, "data": { "index": 40 } }

Picture of my request

但是我无法使其在 Python 上运行并从我的传感器恢复数据。

我的Python代码:

import requests
import json

url = 'http://192.168.1.100/iolink/sickv1' # Address of the OctoPrint Server
header = {'portNumber': '3', 'Content-Type': 'application/json'} #Basic request's header
data = {'index': 40}


def get_sensor_measure():

r = requests.post(url + '/readPort', headers=header, data=data)

print(r.content)
print(r.status_code)

我收到错误:

b'{"header":{"status":1,"message":"Parsing Failed"}}'

提前谢谢

最佳答案

您应该在 data 中传递 'portNumber': '3',而不是在 header 中传递:

header = {'Content-Type': 'application/json'}
data = {'header': {'portNumber': '3'}, 'data': {'index': 40}}

也如 Karl在他的回答中指出,您需要将 data 更改为 json:

r = requests.post(url + '/readPort', headers=header, json=data)

关于python - 如何将http请求转换为Python?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59752459/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com