可视c ++ cURL网页源代码到String ^ [英] visual c++ cURL webpage source to String^
本文介绍了可视c ++ cURL网页源代码到String ^的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在寻找解决方案,如何将网站读取到system :: String ^
Im' looking for solution how to read website to system::String^
我发现curl变成了std :: string的想法,但是在转换链接器后有一些错误; /
i found curl to std::string idea but after converting linker has a few errors ;/
这是我的代码:
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());
}
推荐答案
如果使用的是。 NET,为什么不使用它进行下载?
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;
}
如果由于某些原因必须使用cURL,这应该可以工作
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;
}
这篇关于可视c ++ cURL网页源代码到String ^的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文