2011-04-26 125 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