Getting http get response header

Hi. I have a problem with the http header

I am using following function to get the http header of the Mesh-Node-Mac, but I found the output of the http get header is 0.

void httpHeader()
{
  if (WiFi.isConnected())
  {
    HTTPClient http;

    http.begin("http://192.168.1.34:80/mesh_info");

    http.addHeader("Content-Type", "application/json");
    int httpResponseCode = http.GET();
    Serial.println(http.getString());
    Serial.println(http.header("Mesh-Node-Mac"));

    http.end();
  }

}

and the output is below.

{"status_code":0}
0
{"status_code":0}
0
{"status_code":0}
0

I have use same url "http://192.168.1.34:80/mesh_info" in postman to check the result.

Postman can display the header as below.

I have try all function below in HTTPClient.h but none is working

    /// Response handling
    void collectHeaders(const char* headerKeys[], const size_t headerKeysCount);
    String header(const char* name);   // get request header value by name
    String header(size_t i);              // get request header value by number
    String headerName(size_t i);          // get request header name by number
    int headers();                     // get header count
    bool hasHeader(const char* name);  // check if header exists

Any result for that.

I am using ESP32 Wroom and PIO as development.

Thanks
Samuel

Which platform / HTTP library are you using?

The getString() call might read from the stream and empty the incoming buffer, skipping the headers that are then no longer available to scan (possibly)..

what happens if you do

void httpHeader()
{
  if (WiFi.isConnected())
  {
    HTTPClient http;

    http.begin("http://192.168.1.34:80/mesh_info");

    http.addHeader("Content-Type", "application/json");
    int httpResponseCode = http.GET();
    Serial.println(http.header("Mesh-Node-Mac"));
    Serial.println(http.getString());

    http.end();
  }

}

or may be you need to collectHeaders() first?

Try printing out httpResponseCode after the GET. If it isn't 200 then something went wrong with the request and you can't expect the response header to contain your data.

It seems the request works since the JSON is printed out

The issue is with the 0 afterwards which I suspect is due to not caching the headers as they were coming in

@J-M-L Just found out that the collectHeaders is needed to call before the getting the header.

Changed to the following and seem ok now.

        const char *headerKeys[] = {"Mesh-Node-Mac"};
        const size_t headerKeysCount = sizeof(headerKeys) / sizeof(headerKeys[0]);
        http.collectHeaders(headerKeys, headerKeysCount);
        int httpResponseCode = http.GET();
        Serial.println(http.getString());
        Serial.println(http.headers());
        Serial.println(http.header("Mesh-Node-Mac"));

Good - glad the hint Worked out.
Enjoy your Arduino !

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.