[转]C++ 使用 curl 进行 http 请求(GET、POST、Download)的封装
原文连接:https://www.cnblogs.com/oftenlin/p/9478067.html
CommonTools.h
* CommonTools.h
*
* Created on: 2018年8月2日
* Author: didi
*/
#include <iostream>
#include <curl/curl.h>
#include "zlib.h"
#include <vector>
#include <string>
#include <unistd.h>
#include <memory.h>
#include <json/json.h>
#include <sstream>
using namespace std; class CommonTools{
public:
CommonTools();
~CommonTools();
public:
static size_t receive_data(void *contents, size_t size, size_t nmemb, void *stream);
// HTTP 下载文件的回掉函数
static size_t writedata2file(void *ptr, size_t size, size_t nmemb, FILE *stream);
// 文件下载接口
static int download_file(const char* url, const char outfilename[FILENAME_MAX]);
// http get 请求
static CURLcode HttpGet(const std::string & strUrl, std::string & strResponse,int nTimeout);
// htpp post 请求
static CURLcode HttpPost(const std::string & strUrl, std::string szJson,std::string & strResponse,int nTimeout);
}
CommonTools.cpp
using namespace std;
size_t CommonTools::receive_data(void *contents, size_t size, size_t nmemb, void *stream){
string *str = (string*)stream;
(*str).append((char*)contents, size*nmemb);
return size * nmemb;
}
size_t CommonTools::writedata2file(void *ptr, size_t size, size_t nmemb, FILE *stream) {
size_t written = fwrite(ptr, size, nmemb, stream);
return written;
}
int CommonTools::download_file(const char* url, const char outfilename[FILENAME_MAX]){
CURL *curl;
FILE *fp;
CURLcode res;
/* 调用curl_global_init()初始化libcurl */
res = curl_global_init(CURL_GLOBAL_ALL);
if (CURLE_OK != res)
{
printf("init libcurl failed.");
curl_global_cleanup();
return -1;
}
/* 调用curl_easy_init()函数得到 easy interface型指针 */
curl = curl_easy_init();
if (curl) {
fp = fopen(outfilename,"wb");
/* 调用curl_easy_setopt()设置传输选项 */
res = curl_easy_setopt(curl, CURLOPT_URL, url);
if (res != CURLE_OK)
{
fclose(fp);
curl_easy_cleanup(curl);
return -1;
}
/* 根据curl_easy_setopt()设置的传输选项,实现回调函数以完成用户特定任务 */
res = curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, CommonTools::writedata2file);
if (res != CURLE_OK){
fclose(fp);
curl_easy_cleanup(curl);
return -1;
}
/* 根据curl_easy_setopt()设置的传输选项,实现回调函数以完成用户特定任务 */
res = curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp);
if (res != CURLE_OK)
{
fclose(fp);
curl_easy_cleanup(curl);
return -1;
}
res = curl_easy_perform(curl);
// 调用curl_easy_perform()函数完成传输任务
fclose(fp);
/* Check for errors */
if(res != CURLE_OK){
fprintf(stderr, "curl_easy_perform() failed: %s\n",curl_easy_strerror(res));
curl_easy_cleanup(curl);
return -1;
}
/* always cleanup */
curl_easy_cleanup(curl);
// 调用curl_easy_cleanup()释放内存
}
curl_global_cleanup();
return 0;
}
CURLcode CommonTools::HttpGet(const std::string & strUrl, std::string & strResponse,int nTimeout){
CURLcode res;
CURL* pCURL = curl_easy_init();
if (pCURL == NULL) {
return CURLE_FAILED_INIT;
}
curl_easy_setopt(pCURL, CURLOPT_URL, strUrl.c_str());
//curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);
curl_easy_setopt(pCURL, CURLOPT_NOSIGNAL, 1L);
curl_easy_setopt(pCURL, CURLOPT_TIMEOUT, nTimeout);
curl_easy_setopt(pCURL, CURLOPT_NOPROGRESS, 1L);
curl_easy_setopt(pCURL, CURLOPT_WRITEFUNCTION, CommonTools::receive_data);
curl_easy_setopt(pCURL, CURLOPT_WRITEDATA, (void*)&strResponse);
res = curl_easy_perform(pCURL);
curl_easy_cleanup(pCURL);
return res;
}
CURLcode CommonTools::HttpPost(const std::string & strUrl, std::string szJson,std::string & strResponse,int nTimeout){
CURLcode res;
char szJsonData[1024];
memset(szJsonData, 0, sizeof(szJsonData));
strcpy(szJsonData, szJson.c_str());
CURL* pCURL = curl_easy_init();
struct curl_slist* headers = NULL;
if (pCURL == NULL) {
return CURLE_FAILED_INIT;
}
CURLcode ret;
ret = curl_easy_setopt(pCURL, CURLOPT_URL, strUrl.c_str());
// std::cout << ret << std::endl;
ret = curl_easy_setopt(pCURL, CURLOPT_POST, 1L);
headers = curl_slist_append(headers,"content-type:application/json");
ret = curl_easy_setopt(pCURL, CURLOPT_HTTPHEADER, headers);
ret = curl_easy_setopt(pCURL, CURLOPT_POSTFIELDS, szJsonData);
//curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);
ret = curl_easy_setopt(pCURL, CURLOPT_TIMEOUT, nTimeout);
ret = curl_easy_setopt(pCURL, CURLOPT_WRITEFUNCTION, CommonTools::receive_data);
ret = curl_easy_setopt(pCURL, CURLOPT_WRITEDATA, (void*)&strResponse);
res = curl_easy_perform(pCURL);
curl_easy_cleanup(pCURL);
return res;
}
使用方法
Main.cpp
string strURL = "http://www.baidu.com";
string strResponse;
CURLcode nRes = CommonTools::HttpGet(strURL, strResponse,300);
size_t nSrcLength = strResponse.length(); //下载文件
string strURL = "http://www.baidu.com/aaa.dat";
char local_file[50] = {0};
sprintf(local_file,"./pb_%d_%s.dat",1,"aaaa");
int iDownlaod_Success = CommonTools::download_file(url.c_str(),local_file);
if(iDownlaod_Success<0){
char download_failure_info[100] ={0};
sprintf(download_failure_info,"download file :%s ,failure,url:",local_file,url);
FATAL(download_failure_info);
}
C++用libcurl通过HTTP以表单的方式Post数据到服务器
一、Post 字符串
#include <stdio.h>
#include <curl/curl.h> int main(void)
{
CURL* curl = NULL;
CURLcode res; curl = curl_easy_init();
if(curl == NULL)
{
return CURLE_FAILED_INIT;
} struct curl_slist* headerlist = NULL; // 设置表头,表头内容可能不同
headerlist = curl_slist_append(headerlist, "Content-Type:application/x-www-form-urlencoded");
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headerlist); // 设置URL
curl_easy_setopt(curl, CURLOPT_URL, "http://postit.example.com/moo.cgi"); // 设置参数,比如"ParamName1=ParamName1Content&ParamName2=ParamName2Content&..."
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, "name=daniel&project=curl"); // 设置为Post
curl_easy_setopt(curl, CURLOPT_POST, ); // 发送
res = curl_easy_perform(curl); if(res != CURLE_OK)
{
// 获取详细错误信息
char* szErr = curl_easy_strerror(res);
fprintf(stderr, "curl_easy_perform() failed: %s\n", szErr);
} // 清空
curl_easy_cleanup(curl); // 释放表头
curl_slist_free_all (headerlist); return ;
}
二、Post 文件
#include <stdio.h>
#include <curl/curl.h> size_t OnWriteData(void* buffer, size_t size, size_t nmemb, void* lpVoid); int main(void)
{
CURL* curl = NULL;
CURLcode res; curl = curl_easy_init();
if(curl == NULL)
{
return CURLE_FAILED_INIT;
} struct curl_slist* headerlist = NULL;
struct curl_httppost* formpost = NULL;
struct curl_httppost* lastptr = NULL;
std::string strResponse; // 回复 curl_formadd(&formpost, &lastptr,
CURLFORM_COPYNAME, "ParamName1",
CURLFORM_COPYCONTENTS, "ParamName1Content", CURLFORM_END); curl_formadd(&formpost, &lastptr,
CURLFORM_COPYNAME, "ParamName2",
CURLFORM_COPYCONTENTS, "ParamName2Content", CURLFORM_END); curl_formadd(&formpost, &lastptr,
CURLFORM_COPYNAME, "ParamName3",
CURLFORM_COPYCONTENTS, "ParamName3Content", CURLFORM_END); curl_formadd(&formpost, &lastptr,
CURLFORM_COPYNAME, "registerImgs",
CURLFORM_FILE, "C:/Image.png", CURLFORM_END); // 设置要上传的文件 // 设置表单参数
curl_easy_setopt(curl, CURLOPT_HTTPPOST, formpost); // 设置表头,表头内容可能不同
headerlist = curl_slist_append(headerlist, "Content-Type:application/x-www-form-urlencoded");
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headerlist); // 设置URL
curl_easy_setopt(curl, CURLOPT_URL, "http://postit.example.com/moo.cgi"); // 设置参数,比如"ParamName1=ParamName1Content&ParamName2=ParamName2Content&..."
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, "name=daniel&project=curl"); // 设置为Post
curl_easy_setopt(curl, CURLOPT_POST, ); curl_easy_setopt(curl, CURLOPT_READFUNCTION, NULL);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, OnWriteData);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void*)&strResponse);
curl_easy_setopt(curl, CURLOPT_NOSIGNAL, );
curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, );
curl_easy_setopt(curl, CURLOPT_TIMEOUT, ); // 发送
res = curl_easy_perform(curl); if(res != CURLE_OK)
{
// 获取详细错误信息
char* szErr = curl_easy_strerror(res);
fprintf(stderr, "curl_easy_perform() failed: %s\n", szErr);
} // 清空
curl_easy_cleanup(curl); // 释放表单
curl_formfree(formpost); // 释放表头
curl_slist_free_all (headerlist); return ;
} size_t OnWriteData(void* buffer, size_t size, size_t nmemb, void* lpVoid)
{
std::string* str = dynamic_cast<std::string*>((std::string *)lpVoid);
if( NULL == str || NULL == buffer )
{
return -;
} char* pData = (char*)buffer;
str->append(pData, size * nmemb);
return nmemb;
}
[转]C++ 使用 curl 进行 http 请求(GET、POST、Download)的封装的更多相关文章
- curl获取http请求的状态码
$curl = curl_init(); curl_setopt($curl, CURLOPT_URL, $url); //设置头文件的信息作为数据流输出 curl_setopt($curl, CUR ...
- php curl模拟post请求提交数据样例总结
在php中要模拟post请求数据提交我们会使用到curl函数,以下我来给大家举几个curl模拟post请求提交数据样例有须要的朋友可參考參考.注意:curl函数在php中默认是不被支持的,假设须要使用 ...
- php 使用curl发起https请求
今天一个同事反映,使用curl发起https请求的时候报错:“SSL certificate problem, verify that the CA cert is OK. Details: erro ...
- 老李分享:curl发起https请求
老李分享:curl发起https请求 在POPTEST上课的过程中,我们需要本地模拟https请求来完成性能测试,我们用curl来实现,curl是利用URL语法在命令行方式下工作的开源文件传输工具,使 ...
- http 使用curl发起https请求报错的解决办法
使用curl发起https请求的时候报错:“SSL certificate problem, verify that the CA cert is OK. Details: error:1409008 ...
- 用curl获取https请求时出现错误的处理
今天一个同事反映,使用curl发起https请求的时候报错:“SSL certificate problem, verify that the CA cert is OK. Details: erro ...
- curl 发送post请求
curl 发送post请求 curl -X POST "http://localhost:8080/usr3?id=1&name=3&departmentId=2" ...
- curl 发送json请求
curl 发送json请求 这个是在cmd环境下的输入:注意{\"userName\":\"helo\",\"id\":1}中间不能有空格 ...
- php curl模拟post请求的例子
curl 在php中要模拟post请求数据提交我们会使用到curl函数,下面我来给大家举几个curl模拟post请求提交数据例子有需要的朋友可参考参考. 注意:curl函数在php中默认是不被支持的, ...
- [转]使用 curl 发送 POST 请求的几种方式
HTTP 的 POST 请求通常是用于提交数据,可以通过这篇文章来了解各种提交方式:四种常见的 POST 提交数据方式.做 Web 后端开发时,不可避免地要自己给自己发请求来调试接口,这里要记录的内容 ...
随机推荐
- liunx 安装nc/netcat centos安装netcat
如果本文对你有用,请爱心点个赞,提高排名,帮助更多的人.谢谢大家!❤ 如果解决不了,可以在文末进群交流. 1:下载源码包,wget https://sourceforge.net/projects/n ...
- Netlink: 内核与用户空间传输数据的socket协议
https://en.wikipedia.org/wiki/Netlink https://stackoverflow.com/questions/12899055/how-kernel-notify ...
- pip的安装、以及使用方法。
pip类似RedHat里面的yum,安装Python包非常方便.本节详细介绍pip的安装.以及使用方法. 1.pip下载安装 1.1 pip下载 1 # wget "https://py ...
- 类X509Certificate2
X509Certificate2类的初始化. 文章:使用X509Certificate2类操作证书文件 参考:https://docs.microsoft.com/zh-cn/dotnet/api/s ...
- 微信小程序和APP优劣势大对比
小程序的优势: 1. 无需下载,随走随关 2. 功能丰富,体验更简便 3. 接口众多,可以进行不断的开发 4. 流量入口大,背靠日活9.6亿的微信 5. 有强大的微信生态环境 小程序对比APP的好处: ...
- monkey+shell命令解析总结
结束monkey方法 Linux下: adb shell top | grep monkey windows下: 1.adb shell top | find "monkey" 5 ...
- CodeForces - 83D:Numbers (数学&递归 - min25筛 )
pro:给定三个整数L,R,P求[L,R]区间的整数有多少个是以P为最小因子的.L,R,P<2e9; sol: 一: 比较快的做法是,用函数的思想递归. 用solve(N,P)表示求1到N有多少 ...
- LeetCode 1079. Letter Tile Possibilities
原题链接在这里:https://leetcode.com/problems/letter-tile-possibilities/ 题目: You have a set of tiles, where ...
- 在WinDbg里使用MEX调试扩展
简介 针对WinDbg的MEX调试扩展可以帮助您简化常见的调试器任务,并为调试器提供强大的文本筛选功能.此扩展被Microsoft支持工程师广泛用于解决流程应用程序的故障. 下载&安装 下载m ...
- 使用jmx-exporter&&jmxtrans && nexus jmx 暴露nexus 系统指标信息
以下演示一个简单的使用jmxexporter 暴露nexus jmx 指标为prometheus metrics,同时也集成了一个简单的jmxtrans 输出数据到 graphite 环境准备 doc ...