简体   繁体   English

如何将http请求转换为Python?

[英]How to convert http request to Python?

I need your help.我需要你的帮助。

I am looking to communicate with a REST API containing sensor data at port number 3. I have a Json (POST) request that works perfectly executed on a REST client like Insomnia.我希望在端口号 3 上与包含传感器数据的 REST API 进行通信。我有一个 Json (POST) 请求,它可以在像 Insomnia 这样的 REST 客户端上完美执行。

My request :我的请求 :

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

Picture of my request我的请求图片

However I am unable to make it work on Python and to recover data from my sensor.但是我无法让它在 Python 上工作并从我的传感器恢复数据。

My Python code :我的 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)

I get the error:我收到错误:

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

Thank you in advance先感谢您

You should pass 'portNumber': '3' in data not in header :您应该在data而不是在header传递'portNumber': '3'

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

And also as Karl stated in his answer you need to changes data to json :而且正如Karl在他的回答中所说,您需要将data更改为json

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

My guess would be that you are using the wrong field to pass your payload.我的猜测是您使用了错误的字段来传递您的有效负载。 It isn't really obvious, but the requests package expects JSON-type payload to be sent with the json field, not the data field, ie:这不是很明显,但requests包期望 JSON 类型的有效负载与json字段一起发送,而不是data字段,即:

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

With a few changes (Bold), it works.通过一些更改(粗体),它可以工作。 Thanks谢谢

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

    def get_sensor_measure():

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM