gpt4 book ai didi

c++ - 从 http header 中提取 cookie

转载 作者:行者123 更新时间:2023-11-28 06:55:03 38 4
gpt4 key购买 nike

我正在编写一个 C++ 函数,它将从 http header 中提取 cookie。标题在一个字符串中,看起来像这样:

HTTP/1.1 200 OK
cache-control: no-cache, no-store, max-age=0, must-revalidate
content-language: en
content-length: 3202
content-type: text/html; charset=utf-8
date: Fri, 25 Apr 2014 13:31:44 GMT
etag: "46ec0cd3920851f7b63dbaa70280cd32"
expires: Mon, 01 Jan 1990 00:00:00 GMT
pragma: no-cache
server: tfe
set-cookie: d=32; path=/; expires=Sat, 25-Apr-2015 13:31:44 GMT
set-cookie: req_country=United+Kingdom; path=/; expires=Sun, 25-May-2014 13:31:44 GMT

我需要这个函数来查找 cookies:

set-cookie: d=32; path=/; expires=Sat, 25-Apr-2015 13:31:44 GMT
set-cookie: req_country=United+Kingdom; path=/; expires=Sun, 25-May-2014 13:31:44 GMT

然后将它们放入另一个看起来像这样的字符串中:

d=32; req_country=United+Kingdom;

每个 header 中也可以有 2 个以上的 cookie。

我试过:

size_t p1 = header_data.find("set-cookie:");
size_t p2 = header_data.find(";");

std::string head = header_data.substr(p1,p2-p1);

执行后出现以下错误:

terminate called after throwing an instance of 'std::out_of_range'
what(): basic_string::substr
Aborted (core dumped)

最佳答案

试试这段代码。未优化,但我想它可以按照您想要的方式工作:

#include <iostream>
#include <vector>
#include <sstream>

using namespace std;

std::vector<std::string> &split(const std::string &s, char delim, std::vector<std::string> &elems) {
std::stringstream ss(s);
std::string item;
while (std::getline(ss, item, delim)) {
elems.push_back(item);
}
return elems;
}


std::vector<std::string> split(const std::string &s, char delim) {
std::vector<std::string> elems;
split(s, delim, elems);
return elems;
}

int main() {
std::string header =
"HTTP/1.1 200 OK\n"
"cache-control: no-cache, no-store, max-age=0, must-revalidate\n"
"content-language: en\n"
"content-length: 3202\n"
"content-type: text/html; charset=utf-8\n"
"date: Fri, 25 Apr 2014 13:31:44 GMT\n"
"etag: \"46ec0cd3920851f7b63dbaa70280cd32\"\n"
"expires: Mon, 01 Jan 1990 00:00:00 GMT\n"
"pragma: no-cache\n"
"server: tfe\n"
"set-cookie: d=32; path=/; expires=Sat, 25-Apr-2015 13:31:44 GMT\n"
"set-cookie: req_country=United+Kingdom; path=/; expires=Sun, 25-May-2014 13:31:44 GMT\";\n";

vector<string> headerLines = split(header, '\n');

for (int i(0); i != headerLines.size(); ++i) {
if (headerLines[i].find("set-cookie:") != std::string::npos) {
std::string variablesPart = split(split(headerLines[i], ';')[0], ':')[1];
std::cout << "\nExtracted: {" << variablesPart << "}";
}
}
}

关于c++ - 从 http header 中提取 cookie,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23295707/

38 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com