解析浏览器请求头在c++

Parsing browser request header in C++

本文关键字:c++ 请求 浏览器      更新时间:2023-10-16

我在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)。

谢谢!

一个简单的例子:

#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;
}

这里定义了一个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>>

您想要的位将始终是就在GET之后,您将需要在标题中搜索字符串"Cookie:"