从http标头中提取cookie

时间:2014-04-25 14:17:46

标签: c++ string

我正在编写一个C ++函数,它将从http标头中提取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

我需要此功能才能找到cookie:

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;

每个标题中还可以有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)

1 个答案:

答案 0 :(得分:1)

试试这段代码。没有优化,但我想它的工作方式你想要:

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