解析HTTP字符串

时间:2016-08-07 21:06:49

标签: c string http parsing get

如何解析此字符串GET /STA/ID=HelloWorld/Pass=Testin123 HTTP/1.1首先,我需要检查STA,如果存在,则继续扫描字符串。在这种情况下,ID的值HelloWorld应存储在char数据类型SSID中,值PassTestin123应存储在char中数据类型Pass

首先应确认字符串中是否存在STA。如果不存在,请不要进入循环。如果退出,请搜索IDPass。存放它。

现在问题是我无法存储IDpass的值。也无法搜索STA

char GetString[] = "GET /STA/ID=Test/Pass=123 HTTP/1.1";

char *get = strtok(GetString, " ");
char *request = strtok(NULL, " ");
char *rtype = strtok(NULL, " ");
char *FirstPart;

int main()
{
 if (request != NULL)
 {
  FirstPart = strtok(request,"/");
  while(FirstPart)
   {
   if (!strncmp(part, "STA"))
       {
         //Print STA Found

          if(!strncmp(part, "ID=", 3))
             {
              //Store value of ID
             }

           if(!strncmp(part, "Pass=", 5))
             {
             //Store the Pass
             }
          }
       }
       FirstPart =strtok(NULL,'/');
   }
 } 

1 个答案:

答案 0 :(得分:1)

需要一点清理。一个提示:用编译器切换所有警告和错误,它们存在是有原因的。你的代码甚至没有编译,这是最小的条件。

但是:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
  char GetString[] = "GET /STA/ID=Test/Pass=123 HTTP/1.1";
  // you cannot do it globally in that way, so I pulled it all into main()
  char *request, *FirstPart;
  // please don't use all upper-case for normal variables
  // I did it for some clarity here
  char *ID, *PASS;

  // skip "GET"
  strtok(GetString, " ");
  // get first part
  request = strtok(NULL, " ");

  if (request != NULL) {
    FirstPart = strtok(request, "/");
    // check for base condition
    if (!strncmp(FirstPart, "STA", 3)) {
      //Print STA Found
      printf("STA = %s\n", FirstPart);
    } else {
      fprintf(stderr, "STA not found!\n");
      exit(EXIT_FAILURE);
    }
    FirstPart = strtok(NULL, "/");
    // graze the key-value combinations
    while (FirstPart) {
      // We check them all here, one after the other
      if (!strncmp(FirstPart, "ID=", 3)) {
    //Store value of ID
    ID = strchr(FirstPart, '=');
    // ID is now "=Test", so skip '='
    ID++;
    printf("ID = %s, value of ID = %s\n", FirstPart, ID);
      } else if (!strncmp(FirstPart, "Pass=", 5)) {
    //Store the Pass
    PASS = strchr(FirstPart, '=');
    // PASS is now "=123", so skip '='
    PASS++;
    printf("PASS = %s, value of PASS = %s\n", FirstPart, PASS);
      } else {
    printf("Unknown part \"%s\", ignoring\n", FirstPart);
      }
      FirstPart = strtok(NULL, "/");
    }
  } else {
    fprintf(stderr, "No input at all\n");
    exit(EXIT_FAILURE);
  }
  exit(EXIT_SUCCESS);
}

指针IDPASS仅指向以null结尾的值,它们不是独立的内存。您可以使用malloc()获取一些并使用strlen()衡量金额。以ID为例:ptr_to_mem_for_ID = malloc(strlen(ID));