我想你想解析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
這是最有幫助,謝謝。原來的問題是我有一個URL與查詢字符串。從它我需要創建,上面提到的GET字符串。網址有/搜索?和GET開始於/ search ?.那麼解析規則是尋找第一個單獨的/還是其他的+? +查詢字符串是GET語句的樣子?我知道這聽起來像一個問題的bizzare,但我所試圖做的是不那麼容易,至少對我來說,來解釋。 – reza 2011-04-27 14:24:11
@reza:謝謝你的澄清。我已經相應地修改了我的答案。讓我知道你是否需要任何幫助。 – Gregg 2011-04-27 23:36:28