2012-06-09 68 views
0

林」尋找解決方案如何閱讀網站系統::字符串^的Visual C++捲曲網頁源爲String^

我發現捲曲的std :: string的想法,但轉換後的接頭有幾個錯誤;/

這裏是我的代碼:

using namespace std; 

string contents; 
size_t handle_data(void *ptr, size_t size, size_t nmemb, void *stream) 
{ 
    int numbytes = size*nmemb; 
    // The data is not null-terminated, so get the last character, and replace 
    // it with '\0'. 
    char lastchar = *((char *) ptr + numbytes - 1); 
    *((char *) ptr + numbytes - 1) = '\0'; 
    contents.append((char *)ptr); 
    contents.append(1,lastchar); 
    *((char *) ptr + numbytes - 1) = lastchar; // Might not be necessary. 
    return size*nmemb; 
} 

..

 CURL* curl = curl_easy_init(); 
if(curl) 
    { 
     // Tell libcurl the URL 
     curl_easy_setopt(curl,CURLOPT_URL, "google.com"); 
     // Tell libcurl what function to call when it has data 
     curl_easy_setopt(curl,CURLOPT_WRITEFUNCTION,handle_data); 
     // Do it! 
     CURLcode res = curl_easy_perform(curl); 
     curl_easy_cleanup(curl); 
    textBox2->Text = gcnew String(contents.c_str()); 
    } 

回答

2

如果您使用的.Net你爲什麼不使用它下載?

using namespace System; 
using namespace System::Net; 

int main(array<System::String ^> ^args) 
{ 
    WebClient web; 
    String^ text = web.DownloadString("http://www.google.de"); 
    Console::WriteLine(text); 
    return 0; 
} 

如果必須使用捲曲由於某些原因這應該工作

std::vector<char> LoadFromUrl(const char* url) 
{ 
    struct Content 
    { 
     std::vector<char> data; 
     static size_t Write(char * data, size_t size, size_t nmemb, void * p) 
     { 
      return static_cast<Content*>(p)->WriteImpl(data, size, nmemb); 
     } 

     size_t WriteImpl(char* ptr, size_t size, size_t nmemb) 
     { 
      data.insert(end(data), ptr, ptr + size * nmemb); 
      return size * nmemb; 
     } 
    }; 

    Content content; 

    CURL* curl = curl_easy_init(); 
    curl_easy_setopt(curl, CURLOPT_WRITEDATA, &content); 
    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, &Content::Write); 
    curl_easy_setopt(curl, CURLOPT_URL, url); 
    curl_easy_perform(curl); 

    content.data.push_back('\0'); 

    return content.data; 
} 

int main(array<System::String ^> ^args) 
{ 
    auto content = LoadFromUrl("http://www.google.de"); 
    String^ text = gcnew String(&content.front()); 

    Console::WriteLine(text); 
    return 0; 
}