Home > Mobile >  How to extract relevant info from the body of http response with Arduino?
How to extract relevant info from the body of http response with Arduino?

Time:07-13

I am currently doing a project with Arduino MKR WiFi 1010 and I send a GET request to the server and it sends me back a response contains "clientId". The only info I desire is this client ID. But I am pretty struggling with obtaining it. The complete response is as following:

HTTP/1.1 200 OK
Date: Wed, 13 Jul 2022 07:29:19 GMT
Content-Type: application/json;charset=utf-8
Content-Length: 241
Connection: keep-alive
Cache-Control: no-cache,no-store,must-revalidate
Pragma: no-cache
Expires: -1
X-Content-Type-Options: nosniff
Strict-Transport-Security: max-age=31536000; includeSubDomains
 
[{"ext":{"ack":true},"minimumVersion":"1.0","clientId":"qezkvtxkk8i3csuyirg7bd97jtg","supportedConnectionTypes":["long-polling","smartrest-long-polling","websocket"],"data":null,"channel":"/meta/handshake","version":"1.0","successful":true}] 

As you can see above, the client ID "qezkvtxkk8i3csuyirg7bd97jtg" is what I want. However, I don't know how to extract it. Can someone help me please?

What I have tried so far is following:

void loop() {

  // if there are incoming bytes available
  // from the server, read them and print them:
   while (client.available()) {
   char c = client.read();
   //Serial.print(c);
     if(c=='\n'){
        char c = client.read();
          if(c=='\r'){
             char c = client.read();
                if(c=='\n'){
                   char c = client.read();
                   Serial.print(c);
                  }
            }
      }
   }

}

I tried to allocate the body as the body is separated from the header. But I failed to print the whole body. Instead I just got a "[", the first byte of the body, from the above code.

My idea is to store the body and treat it as a Json Object.

CodePudding user response:

If I understand it well, you retrieve it in a String. So the easiest way to find your client ID is to find the String "clientID" with a provided Arduino's function indexOf, this will give you the index in the String. So on and on you retrieve the string between "clientId":" to ",

mystring.indexOf(val, from)

start = indexOf("\"clientId\":")
indexOf("\",", start)

https://arduinogetstarted.com/reference/arduino-string-indexof

Edit :

To retrieve the whole string from the client you should just do it with a while loop :

  String msg = ""; 
  while ( client.available() ) {
    char c = client.read();
    Serial.print(c);
    msg  = c;
  }
  • Related