封装测试函数
size_t htttp_query_callback(void *buffer, size_t size, size_t nmemb, std::string& content) {
long sizes = size * nmemb;
std::string temp;
temp = std::string((char*)buffer, sizes);
content.append((char*)buffer);
//printf("%s",(char*)buffer);
return sizes;
}
static int my_curl_query(const char* strUrl, std::string& content, int header = 0, int https = 0, const char* strPost = NULL, const char* pCaPath = NULL)
{
CURL *curl;
CURLcode res;
curl = curl_easy_init(); //初始化
if (curl&&strUrl)
{
struct curl_slist *chunk = NULL;
chunk = curl_slist_append(chunk, "Server: Apache/2.4.29 (Win64) PHP/7.0.25 OpenSSL/1.0.2m");
chunk = curl_slist_append(chunk, "X-Powered-By: PHP/7.0.25");
if (0 == header) {
chunk = curl_slist_append(chunk, "Content-Type:application/x-www-form-urlencoded");
std::string accessToken("accessToken:");
accessToken.append("xxxxxxxx");//token
chunk = curl_slist_append(chunk, accessToken.c_str());
}
else if (1 == header) {
chunk = curl_slist_append(chunk, "Content-Type:application/json");
}
else if (2 == header) {
chunk = curl_slist_append(chunk, "Content-Type:application/x-www-form-urlencoded");
}
if (strPost) {
curl_easy_setopt(curl, CURLOPT_POST, 1);
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, strPost); //设置post参数
}
else {
chunk = curl_slist_append(chunk, "Content-length:0");
}
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, chunk);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, htttp_query_callback); //设置回调函数
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &content); //设置写数据
if (https)
{
if (NULL == pCaPath) {
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, false);//设定为不验证证书和HOST
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, false);
}
else {
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 1L);
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 2L);
curl_easy_setopt(curl, CURLOPT_CAINFO, pCaPath);//证书路径
}
}
curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1);
curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1); //设置允许302 跳转
curl_easy_setopt(curl, CURLOPT_URL, strUrl); //设置url地址
res = curl_easy_perform(curl); //执行
if (res != CURLE_OK) {
fprintf(stderr, "curl_easy_perform() failed: %s\n",
curl_easy_strerror(res));
curl_easy_cleanup(curl);
return -1;
}
else {
curl_easy_cleanup(curl);
return 0;
}
}
return -1;
测试
curl_global_init(CURL_GLOBAL_ALL);
std::string content;
my_curl_query("https://www.baidu.com", content,0,1,NULL,"E:\\cacert.pem");
printf("%s\n",content.c_str());
curl_global_cleanup();
get时,把请求加入URL(?deviceId=1000&name=admin)
例子
//https://www.xxxx.com/api/admin?deviceId=1000
my_curl_query("https://www.xxxx.com/api/info?deviceId=1000&name=admin", content,0,1,NULL,"E:\\cacert.pem");
post请求直接传入请求参数(比如json数据)
例子
my_curl_query("https://www.xxxx.com/api/info", content,2,1,"{\"id\":12}","E:\\cacert.pem");
下载后应该包含的头文件和库
#include "curl\curl.h"
#include <stdio.h>
#include <string>
#pragma comment(lib, "libcurl.lib")