HTTP Communication with Server

der_smu
Posts: 1
Joined: Thu Mar 05, 2020 8:31 am

HTTP Communication with Server

Postby der_smu » Thu Mar 05, 2020 8:46 am

Hello,

I want to build a two way communication between an ESP32 and a (Python) server.
The ESP32 shall send a first GET request to the server and according to the server's response call different POST or GET methods.

For the sake of simplicity, I would like to use HTTPclient.h.

Code: Select all

void loop() {

  HTTPClient http;
  http.begin("http://xx.xx.x.xxx:5000/");
  
  int httpCode = http.GET();
  if(httpCode > 0) {
    Serial.printf("[HTTP] GET... code: %d\n", httpCode);
    
    if(httpCode == HTTP_CODE_OK) {
      String payload = http.getString();
      Serial.println(payload);
    }
    
  }else{
    Serial.printf("[HTTP] GET... failed, error: %s\n", http.errorToString(httpCode).c_str());
  }
  
  http.end(); 
}
This code snippets works fine, but here I perform a simple GET on "http://xx.xx.x.xxx:5000/". What's the correct way to then perform a GET or POST on e.g. "http://xx.xx.x.xxx:5000/one" or "http://xx.xx.x.xxx:5000/two"?

Do I have to end my HTTPClient and start a new connection with http.begin():

Code: Select all

void loop() {

  HTTPClient http;
  http.begin("http://10.42.0.191:5000/");
  
  int httpCode = http.GET();
  if(httpCode > 0) {
    Serial.printf("[HTTP] GET... code: %d\n", httpCode);
    
    if(httpCode == HTTP_CODE_OK) {
      String payload = http.getString();
      Serial.println(payload);
      http.end();

      [...]
      
      http.begin("http://10.42.0.191:5000/one");
      int httpCode = http.GET();
      [...]
      http.end();
    }
    
  }else{
    Serial.printf("[HTTP] GET... failed, error: %s\n", http.errorToString(httpCode).c_str());
  }
  
  http.end(); 
  delay(500);
}
This does not look right for me, because - as I understand it - I want to reuse the same connection and not build up a new connection.

Thanks for your help!

Who is online

Users browsing this forum: Bing [Bot] and 98 guests