Ad

Http Request Send By OkHttp Not Received On Micropython Server

I currently try to write a android app to setup and controll a ESP8266 on which micropython runs.
On the micropython server I initialize a websocket like this:

    def __init__(self, task_manager, setup_mode):
        address = socket.getaddrinfo('0.0.0.0', 80)[0][-1]
        self._socket = socket.socket()
        self._socket.bind(address)
        self._socket.listen(1)
        self._socket.setblocking(False)
        self._socket.settimeout(5)

        self._task_manager = task_manager

        self._setup_mode = setup_mode

        print('New Socket is listening on: ', address)

And then simple listen to incoming connections like this, and then react to the incoming messages. Also the listing is looped to allow the microcontroller logic to update every 5 seconds.

client, address = self._socket.accept()
print("New request from:", address)

Everything is working fine when I send test request using python from my PC. For example a simple request would be something like this:

data = json.dumps({'load': {'type': "is_lighthub", 'data': {}}})
response = requests.post(ip, json=data)

However when I try to make the same post request using OkHttp from an android app, then there is no incoming connection at the ESP.
Here is the android java code:

private void addIfLighthub(final InetAddress address) {
        try {
            RequestBody body = RequestBody.create(JSON, "{\"load\": {\"type\": \"is_lighthub_server\", \"data\": {}}");
            Request request = new Request.Builder()
                    .url("http://" + address.getHostAddress())
                    .post(body)
                    .build();
            try (Response response = client.newCall(request).execute()) {
                final JSONObject myResponse = new JSONObject(response.body().string());
                if((boolean)myResponse.get("is_lighthub")) {
                    onlineDeviceList.add(address);
                }
            } catch (IOException e) {
                System.out.println(e.getMessage());
            }
        } catch (JSONException jsonException) {
            System.out.println(jsonException.getMessage());
        }
    }

The odd thing however is that that sample code, if provided with for example the address of my router, does receive the routers default html site ...

So, am I missing something? I fairly new to networking but a simple post request from the phone should be the same as from a python sample code, right?
Or is there a error in my java function?

Thank you guys in advance for the help!

Ad

Answer

If fixed it myself! The mistake was that the python test client sended the json seperate, while the okhttp client sended both in one piece. That made the server timeout while waiting for a second message ...

Ad
source: stackoverflow.com
Ad