无需使用regexp即可解析HTTP请求 [英] Parse HTTP request without using regexp

查看:93
本文介绍了无需使用regexp即可解析HTTP请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用正则表达式来分隔HTTP请求的字段:

I'm using a regex to separate the fields of an HTTP request:

GET /index.asp?param1=hello&param2=128 HTTP/1.1

这种方式:

smatch m;
try 
{ 
    regex re1("(GET|POST) (.+) HTTP"); 
    regex_search(query, m, re1); 
} 
catch (regex_error e) 
{ 
    printf("Regex 1 Error: %d\n", e.code()); 
}
string method = m[1]; 
string path = m[2];

try 
{ 
    regex re2("/(.+)?\\?(.+)?"); 
    if (regex_search(path, m, re2)) 
    { 
        document = m[1]; 
        querystring = m[2];
    }
} 
catch (regex_error e) 
{ 
    printf("Regex 2 Error: %d\n", e.code()); 
}

不幸的是,此代码可在MSVC中使用,但不适用于GCC 4.8.2(我在Ubuntu Server 14.04上具有).您可以建议使用正常的std :: string运算符拆分该字符串的另一种方法吗?

Unfortunately this code works in MSVC but not with GCC 4.8.2 (which I have on Ubuntu Server 14.04). Can you suggest a different method of splitting that string using maybe normal std::string operators?

由于查询字符串分隔符'?',我不知道如何将URL拆分为不同的元素.字符串中可能存在也可能不存在.

I don't know how to split the URL in different elements since the query string separator '?' may or may not be present in the string.

推荐答案

您可以使用std::istringstream对此进行解析:

You might use std::istringstream to parse this:

int main()
{
    std::string request = "GET /index.asp?param1=hello&param2=128 HTTP/1.1";

    // separate the 3 main parts

    std::istringstream iss(request);

    std::string method;
    std::string query;
    std::string protocol;

    if(!(iss >> method >> query >> protocol))
    {
        std::cout << "ERROR: parsing request\n";
        return 1;
    }

    // reset the std::istringstream with the query string

    iss.clear();
    iss.str(query);

    std::string url;

    if(!std::getline(iss, url, '?')) // remove the URL part
    {
        std::cout << "ERROR: parsing request url\n";
        return 1;
    }

    // store query key/value pairs in a map
    std::map<std::string, std::string> params;

    std::string keyval, key, val;

    while(std::getline(iss, keyval, '&')) // split each term
    {
        std::istringstream iss(keyval);

        // split key/value pairs
        if(std::getline(std::getline(iss, key, '='), val))
            params[key] = val;
    }

    std::cout << "protocol: " << protocol << '\n';
    std::cout << "method  : " << method << '\n';
    std::cout << "url     : " << url << '\n';

    for(auto const& param: params)
        std::cout << "param   : " << param.first << " = " << param.second << '\n';
}

输出:

protocol: HTTP/1.1
method  : GET
url     : /index.asp
param   : param1 = hello
param   : param2 = 128

这篇关于无需使用regexp即可解析HTTP请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆