修改自网路

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

#include "CommonTools.h"
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[];
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

// get 请求
string strURL = "http://www.baidu.com";
string strResponse;
CURLcode nRes = CommonTools::HttpGet(strURL, strResponse,);
size_t nSrcLength = strResponse.length(); //下载文件
string strURL = "http://www.baidu.com/aaa.dat";
char local_file[] = {};
sprintf(local_file,"./pb_%d_%s.dat",,"aaaa");
int iDownlaod_Success = CommonTools::download_file(url.c_str(),local_file);
if(iDownlaod_Success<){
char download_failure_info[] ={};
sprintf(download_failure_info,"download file :%s ,failure,url:",local_file,url);
FATAL(download_failure_info);
}

C++ 使用 curl 进行 http 请求(GET、POST、Download)的封装的更多相关文章

  1. curl获取http请求的状态码

    $curl = curl_init(); curl_setopt($curl, CURLOPT_URL, $url); //设置头文件的信息作为数据流输出 curl_setopt($curl, CUR ...

  2. php curl模拟post请求提交数据样例总结

    在php中要模拟post请求数据提交我们会使用到curl函数,以下我来给大家举几个curl模拟post请求提交数据样例有须要的朋友可參考參考.注意:curl函数在php中默认是不被支持的,假设须要使用 ...

  3. php 使用curl发起https请求

    今天一个同事反映,使用curl发起https请求的时候报错:“SSL certificate problem, verify that the CA cert is OK. Details: erro ...

  4. 老李分享:curl发起https请求

    老李分享:curl发起https请求 在POPTEST上课的过程中,我们需要本地模拟https请求来完成性能测试,我们用curl来实现,curl是利用URL语法在命令行方式下工作的开源文件传输工具,使 ...

  5. http 使用curl发起https请求报错的解决办法

    使用curl发起https请求的时候报错:“SSL certificate problem, verify that the CA cert is OK. Details: error:1409008 ...

  6. 用curl获取https请求时出现错误的处理

    今天一个同事反映,使用curl发起https请求的时候报错:“SSL certificate problem, verify that the CA cert is OK. Details: erro ...

  7. curl 发送post请求

    curl 发送post请求 curl -X POST "http://localhost:8080/usr3?id=1&name=3&departmentId=2" ...

  8. curl 发送json请求

    curl 发送json请求 这个是在cmd环境下的输入:注意{\"userName\":\"helo\",\"id\":1}中间不能有空格 ...

  9. php curl模拟post请求的例子

    curl 在php中要模拟post请求数据提交我们会使用到curl函数,下面我来给大家举几个curl模拟post请求提交数据例子有需要的朋友可参考参考. 注意:curl函数在php中默认是不被支持的, ...

  10. [转]使用 curl 发送 POST 请求的几种方式

    HTTP 的 POST 请求通常是用于提交数据,可以通过这篇文章来了解各种提交方式:四种常见的 POST 提交数据方式.做 Web 后端开发时,不可避免地要自己给自己发请求来调试接口,这里要记录的内容 ...

随机推荐

  1. awk删除重复文件

    #!/bin/bash #查找并删除重复文件,每个文件只保留1份 ls -LS --time-style=long-iso | awk 'BEGIN { getline; getline; name1 ...

  2. Python——安居客租房信息爬取(以南昌为例)

    前言: 提前安装好所需要的库. 本代码的输入仅需要某个城市的租房地址首页即可,其他自会生成. 使用前请创建所需的目录,或者为代码添加os.makedir() 支持断点重爬,重行运行即可. header ...

  3. P1972 [SDOI2009]HH的项链

    洛谷的分块练习题 看到讨论中说分块莫队被卡就写了树状数组...(但感觉做法和莫队的思想有点像?) #include<bits/stdc++.h> using namespace std; ...

  4. MySQL sum聚合函数

    select sum(if(money > 0, money, 0)) as money   from total_money 意思是如果money > 0, 将money的值累加到tot ...

  5. day 22 - 1 面向对象

    面向对象 字典实现人狗大战 #定义角色 def Person(name,hp,aggr,sex): person = { 'name':name, 'hp':hp, 'aggr':aggr, 'sex ...

  6. Docker-----仓库

    安装registry 安装并启动docker yum -y install docker systemctl enable docker systemctl start docker 下载regist ...

  7. Pytorch学习笔记(一)---- 基础语法

    书上内容太多太杂,看完容易忘记,特此记录方便日后查看,所有基础语法以代码形式呈现,代码和注释均来源与书本和案例的整理. # -*- coding: utf-8 -*- # All codes and ...

  8. Unsafe 的简单使用

    Unsafe 简介 Unsafe 是sun.misc包中的一个类,可以通过内存偏移量操作类变量/成员变量 Unsafe 用途 AQS(AbstractQueuedSynchronizer) 常用作实现 ...

  9. MySql8.0+全新身份验证方式

    我们在安装MySql8.0+的版本时MySql将会询问我们是否选择全新的身份验证方式,如下图 ⒈第一个是MySql推荐我们使用的强密码加密模式来进行身份验证 MySql8支持基于SHA256改进的更强 ...

  10. 初学python之路-day07-字符编码

    今天的博客主要关于字符编码,并对前几天学习的数据类型做些总结. 学习字符编码的目的:解决乱码问题. 应用程序打开文本文件的三步骤  1.打开应用程序  2.将数据加载到内存中  3.cpu将内存中的数 ...