Convert String to char*

I'm using ESP8266 Library for wifi, and there is a function "send()" to send data to a server.
On this example I'm sending a GET command to query data from a webserver.

String cmd = "GET /u.php?h=";
  cmd += humi;
  cmd += "&t=";
  cmd += temp;
  cmd += "&r=";
  cmd += isRaining;
  cmd += "&rl=";
  cmd += rain;
  cmd += "&g=";
  cmd += gas;
  cmd += "&cycle=";
  cmd += cycle;
  cmd += " HTTP/1.1\r\n";
  cmd += "Host: www.labombarda.org\r\n\r\n";

The point is that the ESP8266.h library works with char* as argument, not String. So I need to convert this.
Doing some researches I made this:

  uint8_t buffer[1024] = {0};
  char __cmd[cmd.length()];
  cmd.toCharArray(__cmd, sizeof(cmd));

However it doesn't seem to work when I try to execute the function:

wifi.send((const uint8_t*)__cmd, strlen(__cmd));

If I print the content of __cmd I get only the first 5 characters, in this case "GET /" all the rest is suppressed.

Any idea on what I'm doing wrong ?

Many thanks,

uint8_t buffer[1024] = {0};

You never use this memory. Why are you allocating it?

You CAN send a GET request one piece at a time. There is no reason to piss away resources collecting all the data in one array, and there is NO reason to do it using a String.

If you just must collect it all together, use sprintf() (and dtostrf() if any of the variables are floats).

How about something like this?

  char *s=(char *)malloc(100); // 100 bytes = max 99 characters long string
  strcpy(s,"hello ");
  strcat(s," world");

Note: do not malloc() over and over again, or you will run out of memory quickly.

Thank you all :slight_smile:

It's resolved

  char __cmd[cmd.length()];
  cmd.toCharArray(__cmd, cmd.length());
  wifi.send((const uint8_t*)__cmd, strlen(__cmd));

But I'll review this further based on your comments Rupert909 and PAulS.

This might be not the most effective way to do it, so I think there is room for improvement even with it working.

Thanks

This might be not the most effective way to do it

You misspelled "definitely is not".

Ok ok, I have to agree :slight_smile: