I am sending a HTTP Request to my WiFi module http://192.168.4.1/STA/ID=HelloWorld/Pass=Testin123
How can I parse above string in Arduino. First I need to check for STA
, if it exists, continue to scan the string. Put Value of ID
, in this case HelloWorld
should be store in String data type SSID
and Value of Pass
, in this case Testin123
should be store in String data type Pass
.
How can achieve above using ARDUINO code! Please help.
1 Answer 1
Your incoming string, as Gerben has mentioned, will actually be more like:
GET /STA/ID=HelloWorld/Pass=Testin123 HTTP/1.1
My personal preferred method is to use strtok()
to split the string up. I'd use a two-pass method for this.
First split the string up into three parts - one GET, one the request, and the third the request type (though you don't need to use that for anything). Assume the string is in C string incoming
:
char *get = strtok(incoming, " ");
char *request = strtok(NULL, " ");
char *rtype = strtok(NULL, " ");
The request is now pointed to by the *request
pointer and the string has been sliced up in-place. So now you can do something similar with the request, this time splitting on /
instead of space:
String SSID;
String Pass;
if (request != NULL) {
char *part = strtok(request, "/");
bool seenSTA = false;
while (part) { // While there is a section to process...
if (seenSTA) {
if (!strncmp(part, "ID=", 3)) { // We have the ID
SSID = String(part + 3);
} else if (!strncmp(part, "Pass=", 5)) { // We have the password
Pass = String(part + 5);
}
} else if (!strcmp(part, "STA")) {
seenSTA = true;
}
part = strtok(NULL, "/");
}
}
-
I thought
Strings
are evil :DSoreDakeNoKoto– SoreDakeNoKoto2016年08月04日 01:26:24 +00:00Commented Aug 4, 2016 at 1:26 -
@TisteAndii they are, which is why I do it all as C strings and then finally convert it to String which Anuj wants (supposedly).Majenko– Majenko2016年08月04日 08:30:33 +00:00Commented Aug 4, 2016 at 8:30
-
@Majenko What about
STA
part? How to check that?MICRO– MICRO2016年08月07日 10:57:40 +00:00Commented Aug 7, 2016 at 10:57 -
The same way as the others, but you don't need to specify the length since it's the entire string you are looking for.
if (!strcmp(part, "STA")) { ... whatever here ... }
Majenko– Majenko2016年08月07日 11:07:58 +00:00Commented Aug 7, 2016 at 11:07 -
@Majenko I tried this but It can't find
STA
in entire link. Always showingNot found
. Here is ArduinoCodeMICRO– MICRO2016年08月07日 12:20:23 +00:00Commented Aug 7, 2016 at 12:20
GET /STA/ID=HelloWorld/Pass=Testin123 HTTP/1.1
, as that is what's send in the http request?strtok()
using/
as the token separator.