1

I send a GET http request to a server and get following data back.

HTTP/1.1 200 
Content-Type: application/json;charset=UTF-8
Transfer-Encoding: chunked
Date: Fri, 16 Nov 2018 16:30:05 GMT
Connection: close

35
{
  "uuid" : "13b29524-7e12-48fb-bbf9-4396aefff45d"
}
0

with the following code I get the header info and the body.

void parseResponse() {
  boolean headerEnd = false;
  byte lineCount = 0;
  String line;
  char endOfLine[] = "\r\n";
  while (1) {
    if (client.available()) {
      char inChar = client.read();
      if (!headerEnd && line.endsWith(endOfLine)) {
        // Just save the first then headers
        if (lineCount == 10) {
          headerEnd = true;
        } else {
          headers[lineCount] = line;
          line = "";
          lineCount++;
        }
      }

      if (line.endsWith("close")) {
        line = "";
        headerEnd = true;
      }

      if (headerEnd && line.endsWith("}")) {
        line.toCharArray(response, sizeof(response));
        client.stop();
        break;
      }

      line += inChar;
    }
  }
}

this thakes 60 - 70ms to parse. Is there a faster way to parse? I think that's slow, for so little text, in the world of AVRs.

5
  • 1
    That doesn't look like C...
    – Shawn
    Nov 16, 2018 at 20:17
  • 2
    The Arduino language is not C, but C++ with some non-standard extensions, such as boolean and byte for bool and unsigned char respectively. Please retag your question.
    – Elias Kosunen
    Nov 16, 2018 at 20:19
  • char lastChar = ""; should be char lastChar = '';. "" is a string, not a char.
    – Barmar
    Nov 16, 2018 at 21:23
  • But the lastChar variable is never used for anything, why do you keep assigning it?
    – Barmar
    Nov 16, 2018 at 21:24
  • @Barmer . Right, I have removed it.
    – Mutus
    Nov 17, 2018 at 9:44

1 Answer 1

3

there are nice functions inherited from Stream class

int parseResponse(char uuid[], int size) {
  if (!client.find("HTTP/1.1")) // skip HTTP/1.1
    return -1;
  int st = client.parseInt(); // parse status code
  int l = -1;
  if (st == 200 && client.find("\"uuid\" : \"")) {
    int l = client.readBytesUntil('"', uuid, size);
    uuid[l] = 0; // terminate the C string
  }
  return l;
}
1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy