2012-07-31 90 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; 
} 
相关问题