我正在尝试编写一个接受HTTP请求并提取少量数据的函数。我的功能如下:
char* handle_request(char * req) {
char * ftoken; // this will be a token that we pull out of the 'path' variable
// for example, in req (below), this will be "f=fib"
char * atoken; // A token representing the argument to the function, i.e., "n=10"
...
// Need to set the 'ftoken' variable to the first arg of the path variable.
// Use the strtok function to do this
ftoken = strtok(req, "&");
printf("ftoken = %s", ftoken);
// TODO: set atoken to the n= argument;
atoken = strtok(NULL, "");
printf("atoken = %s", atoken);
}
req
通常看起来像这样:GET /?f=fib&n=10 HTTP/1.1
目前,在致电strtok()
后,ftoken
打印出GET /?f=fibGET /favicon.ico HTTP/1.1
,这显然是错误的。理想情况下,f=fib
和atoken
将是n=10
任何人都可以帮我解决这个问题吗?
答案 0 :(得分:1)
输入 - > GET /?f=fib&n=10 HTTP/1.1
输出 - > ftoken f=fib
和atoken 10
代码 - >
ftoken = strtok(req, "?"); // This tokenizes the string till ?
ftoken = strtok(NULL, "&"); // This tokenizes the string till &
// and stores the results in ftoken
printf("ftoken = %s", ftoken); // Result should be -> 'f=fib'
atoken = strtok(NULL, "="); // This tokenizes the string till =.
atoken = strtok(NULL, " "); // This tokenizes the string till next space.
printf("atoken = %s", atoken); // Result should be -> 'n=10'