libcurl库的简单使用
#include <stdio.h>
#include <tchar.h>
#include <windows.h>
#include <process.h>
#include <string>
#include <curl.h>
#pragma comment ( lib, "ws2_32.lib" )
#pragma comment ( lib, "wldap32.lib" )
#ifdef _DEBUG
#pragma comment(lib,"libcurld.lib")
#else
#pragma comment(lib,"libcurl.lib")
#endif
size_t write_callback(char* ptr, size_t size, size_t nmemb, std::string& userdata);
int main()
{
CURL* curl;
CURLcode CurlCode;
struct curl_slist* headerlist = NULL;
CurlCode = curl_global_init(CURL_GLOBAL_ALL); //这个函数设置libcurl需要的程序环境 这个函数只能用一次。(其实在调用curl_global_cleanup 函数后仍然可再用)
if (CurlCode != CURLE_OK)return 0;
curl = curl_easy_init(); //初始化
if (curl)
{
curl_easy_setopt(curl, CURLOPT_COOKIEFILE, "");
curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
/*添加请求头*/
//headerlist = curl_slist_append(headerlist, "Content-Type:application/json");
headerlist = curl_slist_append(headerlist, "Accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8");
headerlist = curl_slist_append(headerlist, "Accept-Language:zh-CN,zh;q=0.9");
curl_easy_setopt(curl, CURLOPT_COOKIEJAR, "cookie.txt"); //把服务器发过来的cookie保存到cookie.txt
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headerlist); //设置HTTP请求头
char url[] = "http://www.baidu.com/";
curl_easy_setopt(curl, CURLOPT_URL, url);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_callback); //设置写的回调函数
std::string content;
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &content);
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 1L);//winssl编译时使用windows自带的根证书
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 2L);
CurlCode = curl_easy_perform(curl); //执行请求
printf("%s\r\n", content.c_str());
curl_easy_cleanup(curl); //释放资源
curl_slist_free_all(headerlist);
headerlist = NULL;
}
curl_global_cleanup();//在结束libcurl使用的时候,用来对curl_global_init做的工作清理。类似于close的函数
system("pause");
return 0;
}
size_t write_callback(char* ptr, size_t size, size_t nmemb, std::string& userdata)
{
size_t rest = 0;
LONG lsize = size * nmemb;
std::string stemp(ptr, lsize);
userdata += stemp;
return lsize;
}
下载 libcurl https://curl.haxx.se/download.html
帮助文档 https://curl.haxx.se/libcurl/c/
参考文章:http://blog.csdn.net/dearwind153/article/details/51914985
参考:https://www.cnblogs.com/hongfei/p/3469982.html
注意:如果使用静态连接库的话需要设置 预处理器定义 CURL_STATICLIB

浙公网安备 33010602011771号