-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathparseHttp.cpp
More file actions
68 lines (58 loc) · 1.7 KB
/
Copy pathparseHttp.cpp
File metadata and controls
68 lines (58 loc) · 1.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
#include <vector>
#include <string>
#include <iostream>
using namespace std;
//分割字符串
vector<string> splitString(const string& str,const string& delimiter)
{
vector<string> tokens;
size_t pos = 0;
size_t prev = 0;
while((pos = str.find(delimiter,prev)) != string::npos)
{
tokens.push_back(str.substr(prev,pos - prev));
prev = pos + delimiter.size();
}
tokens.push_back(str.substr(prev));
return tokens;
}
//解析http请求
void parseHttpRequest(const string& request)
{
//分割请求行
vector<string> lines = splitString(request,"\r\n");
vector<string> requestLine = splitString(lines[0]," ");
if(requestLine.size() >= 3)
{
cout << "Method: " << requestLine[0] << endl;
cout << "Path: " << requestLine[1] << endl;
}
cout << "print Headers---------" << endl;
//分割头部字段
for(int i = 1;i < lines.size();i++)
{
vector<string> header = splitString(lines[i],": ");
if(header.size() >= 2)
{
cout << "Header: " << header[0] << " - " << header[1] << endl;
}
}
//找到正文的起始处
size_t bodyStart = request.find("\r\n\r\n");
if(bodyStart != string::npos)
{
string body = request.substr(bodyStart + 4);
cout << "Body: " << body << endl;
}
}
int main()
{
string request = "GET /example HTTP/1.1\r\n"
"Host: www.example.com\r\n"
"Content-Type: application/json\r\n"
"\r\n"
"{\"key\": \"value\"}";
parseHttpRequest(request);
system("pause");
return 0;
}