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

 

posted @ 2021-11-22 18:15  冰糖葫芦很乖  阅读(321)  评论(0编辑  收藏  举报