visual c++ cURL webpage source to String^

可紊 提交于 2019-12-25 04:03:24

问题


Im' looking for solution how to read website to system::String^

i found curl to std::string idea but after converting linker has a few errors ;/

here is my code:

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());
    }

回答1:


If you're using .Net why don't you use it for the download?

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;
}

If you have to use cURL for some reasons this should work

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;
}


来源:https://stackoverflow.com/questions/10961087/visual-c-curl-webpage-source-to-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!