stas95 stas95 - 6 months ago 64
Android Question

NodeMCU server bad response, when sending GET request from Android app

I've made little server based on NodeMCU. All works good, when I'm conneting from browser, but problem starts, when I'm trying to connect from Android app uisng OkHttp or Volley, I'm receiving exceptions.
java.io.IOException: unexpected end of stream on Connection using OkHttp,
EOFException using Volley.

Problem is very similar for this
EOFException after server responds, but answer didn't found.

ESP server code

srv:listen(80, function(conn)

conn:on("receive", function(conn,payload)
print(payload)
conn:send("<h1> Hello, NodeMCU.</h1>")
end)
conn:on("sent", function(conn) conn:close() end)
end)


Android code

final RequestQueue queue = Volley.newRequestQueue(this);
final String url = "http://10.42.0.17:80";





final StringRequest request = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {

@Override
public void onResponse(String response) {
mTemperatureTextView.setText(response.substring(0, 20));
System.out.println(response);
}
},

new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
System.out.println("Error + " + error.toString());
mTemperatureTextView.setText("That didn't work!");
}
}
);





mUpdateButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
queue.add(request);
}
});

Answer

What you're sending back is not HTTP. It's nothing but a protocol-agnostic HTML fragment. Furthermore, there's a memory leak lingering.

Try this instead:

srv:listen(80, function(conn)

  conn:on("receive", function(sck,payload)
    print(payload)
    sck:send("HTTP/1.0 200 OK\r\nServer: NodeMCU on ESP8266\r\nContent-Type: text/html\r\n\r\n<h1> Hello, NodeMCU.</h1>")
  end)
  conn:on("sent", function(sck) sck:close() end)
end)
  • you need to send back some HTTP headers, HTTP/1.0 200 OK and the newlines are mandatory
  • each function needs to use it's own copy of the passed socket instance, see how I renamed conn to sck in the two callback functions, see http://stackoverflow.com/a/37379426/131929 for details

For a more complete send example look at net.socket:send() in the docs. That becomes relevant once you start sending more than just a couple of bytes.