1

I am actually working on an IOT project in which I am using ESP8266 to send data to server. The code does not seem to have any problem but nothing is sent to the server as no update is received on the client application. However, sending data using postman or browser works fine. The code is writen in micropython. Thanks a lot as you take your precious time to assist.

code:

boot.py:

try:
  import usocket as socket
except:
  import socket

from machine import Pin
import network

import esp
esp.osdebug(None)

import gc
gc.collect()

ssid = 'iottollgate'
password = 'iot2017/2018'

station = network.WLAN(network.STA_IF)

station.active(True)
station.connect(ssid, password)

main.py:

def http_get(url):
    import socket
    _, _, host, path = url.split('/', 3)
    addr = socket.getaddrinfo(host, 80)[0][-1]
    s = socket.socket()
    s.connect(addr)
    print(addr)
    full_path = 'POST /%s HTTP/1.1\r\nHost: %s\r\n%s' % ('api/post_data.php', 'www.desopadec.org', 'l=3&t=4&v=2&c=2&l2=27&t2=2&v2=180&c2=9')
    s.send(bytes(full_path, 'utf8'))
    while True:
        data = s.recv(100)
        if data:
            print(str(data, 'utf8'), end='')
        else:
            break
    s.close()

http_get()

1 Answer 1

1
... 'POST /%s HTTP/1.1\r\nHost: %s\r\n%s'

This is not a valid POST request. There must be an empty line to signal the end of the HTTP header, i.e.

... 'POST /%s HTTP/1.1\r\nHost: %s\r\n\r\n%s'

Apart from that it is missing the Content-length header to declare the size of the body or alternatively use of chunked transfer encoding. Currently the server has cannot determine where the request body ends.

Additionally the code assumes that the server will close the connection after sending the response. Given that support for HTTP keep-alive is implicitly announced by using HTTP/1.1, the server might keep the connection open in the hope of another request.

In general: HTTP might look simple but is actually a complex standard. Don't guess what client and server are supposed to do but follow the actual standard, i.e. RFC 7230 and others.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot. Adding an empty line at the end of the header as you suggested solved the problem like so: 'POST /%s HTTP/1.1\r\nHost: %s\r\n\r\n%s'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.