Hi there,
I use HttpClient to get a JSON string from my server. The code used to work well. But these days it does not work. The response body is NULL, however, I can get the right response from BROWSER.
How to debug this problem?
request.hostname = 'SERVER_IP';
request.port = 80;
request.path = "/api/timers?deviceId=" + System.deviceID();
// Get request
http.get(request, response, headers);
Log.trace("Application>\tResponse status: ");
Log.trace("" + response.status);
if (response.status != 200)
return;
Log.trace("Application>\tHTTP Response Body: ");
Log.trace(response.body);
Thanks.
Have you really provided the SERVER_IP
wrapped in single quotes? That won’t work.
Also for nit-picking, an IP is not a hostname. While it should work in more recent versions of HttpClient, previous versions did require you to leave the hostname
field empty (when not providing an actual host name) and alternatively provide the IP in the dedicated request.ip
field.
2 Likes
Yes of course. Neither hostname or ip address works.
This works for me
SYSTEM_MODE(MANUAL)
SYSTEM_THREAD(ENABLED)
#include <HttpClient.h>
HttpClient http;
http_header_t headers[] = {
// { "Content-Type", "application/json" },
// { "Accept" , "application/json" },
{ "Accept" , "*/*"},
{ NULL, NULL } // NOTE: Always terminate headers will NULL
};
http_request_t request;
http_response_t response;
void setup() {
Particle.connect();
}
void loop() {
static uint32_t ms = millis();
if (millis() - ms < 10000) return;
ms = millis();
Serial.println();
Serial.println("Application>\tStart of Loop.");
// Request path and body can be set at runtime or at setup.
//request.hostname = "192.168.1.30";
request.ip = IPAddress(192, 168, 1, 30);
request.port = 80;
request.path = "/index.html";
// Get request
http.get(request, response, headers);
Serial.print("Application>\tResponse status: ");
Serial.println(response.status);
Serial.print("Application>\tHTTP Response Body: ");
Serial.println(response.body);
}
It works to specify the IP using "request.ip". Then how to set hostname?
I don’t know why. But if I use request.hostname, the response status is -1, and the response body is NULL.
Care to elaborate?
Was it ...
yes. I think Particle should give me compilation errors.
For that you may want to talk to gcc.gnu.org as that’s the compiler used 
BTW, you may get warnings like this when writing a string in single quotes already
.ino:32:24: warning: character constant too long for its type
The problem is just that you won’t ever see the warnings when there is no real error in the code.
I sometimes deliberately introduce a syntax error (e.g. an extra {
at the end) in my ortherwise correct code to force Web IDE into showing me the warnings too (by means of the SHOW RAW button).
1 Like