简体   繁体   中英

HTTP post Json 400 Error

I am trying to post data to my server from my microcontroller. I need to send raw http data from my controller and this is what I am sending below:

POST /postpage HTTP/1.1
Host: https://example.com
Accept: */*
Content-Length: 18
Content-Type: application/json

{"cage":"abcdefg"}

My server requires JSON encoding and not form encoded request.

For the above request sent, I get an 400 error from the server, HTTP/1.1 400 Bad Request

However, when I try to reach the post to my server via a python script via my laptop, I am able to get a proper response.

import requests
url='https://example.com'
mycode = 'abcdefg'



def enter():
    value = requests.post('url/postpage', 
                             params={'cage': mycode})
    print vars(value)


enter()

Can anyone please let me know where I could be going wrong in the raw http data I'm sending above ?

HTTP specifies the separator between headers as a single newline, and requires a double newline before the content:

POST /postpage HTTP/1.1
Host: https://example.com
Accept: */*
Content-Length: 18
Content-Type: application/json

{"cage":"abcdefg"}

If you don't think you've got all of the request right, try seeing what was sent by Python:

response = ...
request = response.request # request is a PreparedRequest.
headers = request.headers
url = request.url

Read the docs for PreparedRequest for more information.


To pass a parameter, use this Python:

REQUEST = 'POST /postpage%s HTTP/1.1\r\nHost: example.com\r\nContent-Length: 0\r\nConnection: keep-alive\r\nAccept-Encoding: gzip, deflate\r\nAccept: */*\r\nUser-Agent: python-requests/2.4.3 CPython/2.7.9 Linux/4.4.11-v7+\r\n\r\n';
query = ''
for k, v in params.items():
    query += '&' + k + '=' + v # URL-encode here if you want.
if len(query): query = '?' + query[1:]
return REQUEST % query

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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