C/C++ curl 访问https链接

180it 2021-06-29 PM 1718℃ 0条
#include<iostream>
#include<string>
#include<curl\curl.h>
using namespace std;

 
static size_t downloadCallback(void *buffer, size_t sz, size_t nmemb, void *writer)
{
    string* psResponse = (string*) writer;
    size_t size = sz * nmemb;
    psResponse->append((char*) buffer, size);
 
    return sz * nmemb;
}
 
int main()
{
    
    
    system("chcp 65001");
    system("cls");
    
    string strUrl = "https://www.baidu.com";
    string strTmpStr;
    CURL *curl = curl_easy_init();
    curl_easy_setopt(curl, CURLOPT_URL, strUrl.c_str());
    curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1L);
    curl_easy_setopt(curl, CURLOPT_TIMEOUT, 2);
    // 下面两个为验证对方和验证主机名,若为0,则跳过验证,我这个服务器必须验证才能得到请求数据
    curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L);
    curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, false);
    
    curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1); //1表示重定向次数,最多允许一次重定向
            
    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, downloadCallback); 
    curl_easy_setopt(curl, CURLOPT_WRITEDATA, &strTmpStr);
    CURLcode res = curl_easy_perform(curl);
    curl_easy_cleanup(curl);
    string strRsp;
    if (res != CURLE_OK)
    {
        strRsp = "error";
    }
    else
    {
        strRsp = strTmpStr;
    }
        cout<<strRsp.c_str()<<endl;
    

    return 0;
}
支付宝打赏支付宝打赏 微信打赏微信打赏

如果文章或资源对您有帮助,欢迎打赏作者。一路走来,感谢有您!

标签: none

C/C++ curl 访问https链接