在C ++中解析浏览器请求标头

时间:2012-12-28 02:53:24

标签: c++ string parsing webserver

我在C ++中编写一个简单的Web服务器,我需要解析请求标头。我是怎么做到的?

这是我的标题......

GET /test?username=2 HTTP/1.1
Host: stream.mysite.com:7777
Connection: keep-alive
Cache-Control: max-age=0
User-Agent: Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.97 Safari/537.11
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Encoding: gzip,deflate,sdch
Accept-Language: pt-BR,pt;q=0.8,en-US;q=0.6,en;q=0.4
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3
Cookie: auth=asdfasdfaasdfasd

我需要获取页面(/ test?username = 2)和cookie变量auth的内容(asdfasdfaasdfasd)。

谢谢!

2 个答案:

答案 0 :(得分:4)

一个让你入门的简单例子:

#include <iostream>
#include <string>
#include <sstream>
int main() {
  std::string tk1, tk2, line = "GET /test?username=2 HTTP/1.1";
  std::stringstream ss(line);
  ss >> tk1;
  ss >> tk2;
  if (tk1 == "GET") {
    std::cout << "requested path: " << tk2 << std::endl;
  }
  return 0;
}

答案 1 :(得分:2)

这里定义了一个Http请求:

http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html

基本上你需要知道的是:

GET <URL> <HTTP-Version><CRLF>
<Set of Headers each line terminated with <CRLF>>
<Empty Line with just <CRLF>>

您想要的位将始终是&lt; URL&gt;在GET之后您将需要在标题中搜索字符串“Cookie:”