2011-04-26 127 views
0

什么是解析为HTTP GET参数的URL的正确方法。例如,谷歌的搜索URL和HTTP GET参数

http://www.google.com/search?hl=en&source=hp&biw=1422&bih=700&q=blabla&btnG=Google+Search&aq=f&aqi=&aql=&oq= 

Wireshark的显示

GET /search?hl=en&source=hp&biw=1422&bih=700&q=blabla&btnG=Google+Search&aq=f&aqi=&aql=&oq 

分析逻辑?

回答

1

我想你想解析Request-URI

这里有一个办法做到这一点的C++:

#include <iostream> 
#include <string> 

// Returns the relative Request-URI from url. For example, given the url 
// "http://www.google.com/search?q=xyz", it will return "https://stackoverflow.com/search?q=xyz". 
// 
// url need not be prefixed with a protocol; i.e. "google.com" is valid. 
// 
// If url contains a protocol (i.e. "http://"), the Request-URI begins with the 
// first "/" after the protocol. Otherwise, the Request-URI begins with the 
// first "/". 
// 
// If url does not contain a Request-URI, its Request-URI is "/", the server 
// root. 
std::string ParseRequestUri(const std::string& url) { 
    const std::string protocol_identifier("://"); 

    std::size_t pos = url.find(protocol_identifier); 

    if (pos != std::string::npos) 
    pos = url.find_first_of("/", pos + protocol_identifier.length()); 
    else 
    pos = url.find_first_of("/"); 

    if (pos != std::string::npos) 
    return url.substr(pos); 

    return "/"; 
} 

int main() { 
    const std::string test_url = "http://google.com/search?hl=en&source=hp&biw=1422&bih=700&q=blabla&btnG=Google+Search&aq=f&aqi=&aql=&oq="; 
    const std::string test_url2 = "example.com/path/to/foo/bar/baz.tar.gz"; 

    std::cout << ParseRequestUri(test_url) << std::endl; 
    std::cout << ParseRequestUri(test_url2) << std::endl; 
} 

上面的代码将输出:

/search?hl=en&source=hp&biw=1422&bih=700&q=blabla&btnG=Google+Search&aq=f&aqi=&aql=&oq= 
/path/to/foo/bar/baz.tar.gz 
+0

这是最有帮助,谢谢。原来的问题是我有一个URL与查询字符串。从它我需要创建,上面提到的GET字符串。网址有/搜索?和GET开始于/ search ?.那么解析规则是寻找第一个单独的/还是其他的+? +查询字符串是GET语句的样子?我知道这听起来像一个问题的bizzare,但我所试图做的是不那么容易,至少对我来说,来解释。 – reza 2011-04-27 14:24:11

+0

@reza:谢谢你的澄清。我已经相应地修改了我的答案。让我知道你是否需要任何帮助。 – Gregg 2011-04-27 23:36:28

0

查询字符串是键 - 值对的数组。你可以通过他们获得关键和相应的价值。如果你指定你用什么编程语言,我能提供的代码示例

+0

C++的std :: string – reza 2011-04-27 00:04:30

+0

实际上所有我需要做的是重建的get参数来自网址。 – reza 2011-04-27 00:05:42

+0

抱歉,不C++太强大了。但原则是一样的。获取查询字符串,使用解析器来解析查询字符串字符串转换成使用System.Web.HttpUtility.ParseQueryString查询键值对(如果你可以添加参考),并遍历数组 – Dimitri 2011-04-27 00:23:44