2012-07-31 86 views
0

與將頁面另存爲.xml或查看頁面源時的瀏覽器功能相同。當然,我的目標是一個網頁,是在XML中,並像這樣開始:如何使用C++從互聯網上下載xml

<?xml version="1.0" encoding="UTF-8"?> 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 

爲什麼我要這樣做?嗯,我想某些網頁的整個源轉儲到一個字符串或CString的,這我還是figuring out how to do

+3

退房[的libcurl](http://curl.haxx.se/libcurl/)。 – 2012-07-31 08:38:44

+0

這個問題如何不是另一個問題的完全重複? – 2012-07-31 08:40:30

+0

你已經問了同樣的問題兩次,你得到了相同的'使用libcurl'的好答案。 Libcurl會做你想做的事情,XML或HTML就沒有什麼區別。如果你不準備相信你得到的答案,那麼在論壇上發帖並沒有多大意義。 – jahhaj 2012-07-31 08:40:53

回答

2

既然你提到的Visual C++,一個很好的解決方案將是使使用最近發佈的來自Microsoft Research的HTTP Casablanca庫,前提是您也可以使用C++ 11。

http://msdn.microsoft.com/en-us/devlabs/casablanca.aspx

的,你需要使用一個HTTP客戶端,類似於在本教程中所描述的, http://msdn.microsoft.com/en-US/devlabs/hh977106.aspx

這可以是這樣的,

http_client client(L"http://somewebsite.com"); 

client.request(methods::GET, L"page-to-download.html") 
    .then([](http_response response) { 
     cout << "HTML SOURCE:" << endl << response.to_string() << endl; }) 
    .wait(); 
+0

這比libcurl好多了,我真的很希望標準能夠很快得到這樣的東西。 – 2012-07-31 09:19:21

1

使用libcurl

size_t AppendDataToStringCurlCallback(void *ptr, size_t size, size_t nmemb, void *vstring) 
{ 
    std::string * pstring = (std::string*)vstring; 
    pstring->append((char*)ptr, size * nmemb); 
    return size * nmemb; 
} 

std::string DownloadUrlAsString(const std::string & url) 
{ 
    std::string body; 

    CURL *curl_handle; 
    curl_global_init(CURL_GLOBAL_ALL); 
    curl_handle = curl_easy_init(); 
    curl_easy_setopt(curl_handle, CURLOPT_URL, url.c_str()); 
    curl_easy_setopt(curl_handle, CURLOPT_WRITEFUNCTION, AppendDataToStringCurlCallback); 
    curl_easy_setopt(curl_handle, CURLOPT_WRITEDATA, &body); 
    curl_easy_perform(curl_handle); 
    curl_easy_cleanup(curl_handle); 

    return body; 
} 
相關問題