Accessing Response Headers (HTTPClient)

RamtinPRG
Posts: 1
Joined: Sat Mar 26, 2022 3:06 pm

Accessing Response Headers (HTTPClient)

Postby RamtinPRG » Sat Mar 26, 2022 3:26 pm

Hello, currently I have a problem with accessing headers.
Actually, I wanna have the "Set-Cookie" header responding from the server (I'm using HTTPClient library).
I tried several methods from HTTPClient class (e. g. hasHeader, collectHeaders, headers and header) but I think they only work for request headers.
This is my code:

Code: Select all

#include <WiFi.h>
#include <HTTPClient.h>

const char *ssid = "ssid";
const char *password = "password";

void setup()
{
  Serial.begin(115200);
  delay(4000);
  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED)
  { // Check for the connection
    delay(1000);
    Serial.println("Connecting to WiFi..");
  }

  Serial.println("Connected to the WiFi network");

  if (WiFi.status() == WL_CONNECTED)
  {

    HTTPClient http;
    const char *headerKeys[] = {"Set-Cookie"};
    const size_t numberOfHeaders = 1;

    http.begin("http://server-url/login");                         // Specify destination for HTTP request
    http.addHeader("Content-Type", "application/x-www-form-urlencoded"); // Specify content-type header
    http.addHeader("User-Agent", "ESP32-IOT-Client");                    // Specify User-Agent header
    http.addHeader("Connection", "keep-alive");                          // Specify connection header

    int httpResponseCode = http.POST("username=test&password=test");
    http.collectHeaders(headerKeys, numberOfHeaders);

    if (httpResponseCode > 0)
    {

      String response = http.getString();
      if (http.hasHeader("Set-Cookie"))
        Serial.println("YEAH");
      else
        Serial.println("NOPE");
      for (int i = 0; i < http.headers(); i++)
      {
        Serial.println(http.header(i));
      }
      Serial.println(httpResponseCode);
      Serial.println(response);
    }
    else
    {

      Serial.print("Error on sending POST: ");
      Serial.println(httpResponseCode);
    }

    http.setURL("http://192.168.1.6:8000/");
    httpResponseCode = http.GET();
    if (httpResponseCode > 0)
    {

      String response = http.getString();

      Serial.println(httpResponseCode);
      Serial.println(response);
    }
    else
    {

      Serial.print("Error on sending POST: ");
      Serial.println(httpResponseCode);
    }
  }
  else
  {

    Serial.println("Error in WiFi connection");
  }
}

void loop()
{
  // put your main code here, to run repeatedly:
}

Who is online

Users browsing this forum: Basalt and 71 guests