1. 程式人生 > 其它 >curl 獲取資料

curl 獲取資料

程式碼

#include <stdio.h>
#include <curl/curl.h>
#include <iostream>
using namespace std;
static size_t WriteMemoryCallback(void* ptr, size_t size, size_t nmemb, void* stream)
{
    size_t nsize = size * nmemb;
    std::string* strdata = (std::string*)stream;
    if (strdata)
    {
        strdata
->append((const char*)ptr, nsize); } return nsize; } void what(){ std::string strIpInfo = "https://www.baidu.com/"; CURL* curl = curl_easy_init(); CURLcode res; std::string a = ""; if (curl) { curl_easy_setopt(curl, CURLOPT_URL, strIpInfo.c_str()); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteMemoryCallback); curl_easy_setopt(curl, CURLOPT_WRITEDATA,
&a); res = curl_easy_perform(curl); curl_easy_cleanup(curl); if (res != CURLE_OK) { fprintf(stderr, "curl_easy_perform() failed: %s\n", curl_easy_strerror(res)); } } cout << a << endl; } int main(void) { what(); //cout << a << endl;
return 0; }