Skip to content

天楚锐齿

人工智能 云计算 大数据 物联网 IT 通信 嵌入式

天楚锐齿

  • 下载
  • 物联网
  • 云计算
  • 大数据
  • 人工智能
  • Linux&Android
  • 网络
  • 通信
  • 嵌入式
  • 杂七杂八

Linux下使用curl库做HTTP GET、POST请求

2019-07-12

linux下用c语言,可以使用curl库来实现相关http get、post之类的操作,看例子:

log.h

#ifndef _LOG_GLOBAL_H_
#define _LOG_GLOBAL_H_
#define LOG_DEBUG       1
#define LOG_GLOBAL_PATH “/media/sdcard/license_client/”
#define LOG_GLOBAL_FILE “license_client.log”
#define LOG_GLOBAL_MAX_LINE 100000
extern int InitLog();
extern int UninitLog();
extern void Log(const char *p_fmt, …);
extern void LogHex(char *pData, size_t size);
#endif /*_LOG_GLOBAL_H_*/

log.c

每10万行切换一个log文件名。
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <malloc.h>
#include <stdarg.h>
#include <errno.h>
#include<sys/types.h>
#include <sys/stat.h>
#include <string.h>
#include <time.h>
#include “log.h”
FILE *logGlobalFd = NULL;
unsigned int logGlobalLineNum = 0;
pthread_mutex_t logGlobalMutex;
int InitLog()
{
charlog[256];
#ifdef LOG_DEBUG
if(logGlobalFd){
return1; //already init.
}
mkdir(LOG_GLOBAL_PATH, 0755);
snprintf(log, sizeof(log), “%s/%s”, LOG_GLOBAL_PATH, LOG_GLOBAL_FILE);
logGlobalFd = fopen((char*)log, “a”);
if (!logGlobalFd){
printf(“%s=>%s(): failed to open log file (errno=%s)\n”, __FILE__, __FUNCTION__, strerror(errno));
return-1;
}
printf(“%s=>%s(): creat log file %s sucessfull!\n”, __FILE__, __FUNCTION__, log);
// init mutex
if (pthread_mutex_init(&logGlobalMutex, NULL) !=0){
fclose(logGlobalFd);
printf(“%s=>%s(): init mutex error!\n”, __FILE__, __FUNCTION__);
return-1;
}
#endif //LOG_DEBUG
return1;
}
int UninitLog()
{
#ifdef LOG_DEBUG
if(logGlobalFd){
fclose(logGlobalFd);
pthread_mutex_destroy(&logGlobalMutex);
}
#endif //LOG_DEBUG
return1;
}
static int LogNewLogFile()
{
chartmp[256];
chartmp2[256];
chardate[128];
time_t now;
struct tm ptm;
if (logGlobalFd)
{
fclose(logGlobalFd);
time(&now);
localtime_r(&now,&ptm);
strftime((char*)date, 128, “_%F_%T”, &ptm);
snprintf(tmp, sizeof(tmp), “%s/%s”, LOG_GLOBAL_PATH, LOG_GLOBAL_FILE);
snprintf(tmp2, sizeof(tmp2), “%s_%s.log”, tmp, date);
remove(tmp2);
rename(tmp, tmp2);
logGlobalFd = fopen((char*)tmp, “a”);
}
return1;
}
void Log(const char *p_fmt, …)
{
chardate[256];
time_t now;
struct tm ptm;
va_list ap;
#ifdef LOG_DEBUG
if (!logGlobalFd){
return;
}
pthread_mutex_lock(&logGlobalMutex);
time(&now); // Gets the system time
if (localtime_r(&now, &ptm))
{
strftime(date, sizeof (date), “%F %T”, &ptm);
fprintf(logGlobalFd, “%s “, date);
va_start(ap, p_fmt);
vfprintf(logGlobalFd, p_fmt, ap);
va_end(ap);
fflush(logGlobalFd);
logGlobalLineNum++;
if (logGlobalLineNum > LOG_GLOBAL_MAX_LINE){
LogNewLogFile();
logGlobalLineNum = 0;
}
}
pthread_mutex_unlock(&logGlobalMutex);
#endif //LOG_DEBUG
return;
}
void LogHex(char *pData, size_t size)
{
    size_t i;
    size_t c;
    unsigned int width=0x10;
    char lineStr[128];
   for(i=0; i<size; i+= width) {
        sprintf(lineStr, ” %8.8lX: \0″, (long)i);
        /* show hex to the left */
        for(c = 0; c < width; c++) {
            if(i+c < size)
                sprintf(lineStr+strlen(lineStr), “%02X \0”, pData[i+c]);
            else
                sprintf(lineStr+strlen(lineStr), ” \0″);
        }
        sprintf(lineStr+strlen(lineStr), ” \0″);
        /* show data on the right */
        for(c = 0; (c < width) && (i+c < size); c++) {
            char x = (pData[i+c] >= 0x20 && pData[i+c] < 0x80) ? pData[i+c] : ‘.’;
            sprintf(lineStr+strlen(lineStr), “%c\0”, x);
        }
        sprintf(lineStr+strlen(lineStr), “\n\0”);
        Log(“DEBUG %s”, lineStr); /* newline */
    }
    Log(“DEBUG \n”); /* space line */
}

EasyCurl.h

基于网上代码修改而来的。
#ifndef __EASY_CURL_H__
#define __EASY_CURL_H__
#include <string>
#include <functional>
#include <tr1/memory>
#include <tr1/functional>
using std::string;
class IProgressCallback
{
public:
    virtual bool OnProgressCallback(int nValue) = 0;
};
class EasyCurl
{
public:
    EasyCurl(void);
    ~EasyCurl(void);
    typedef std::tr1::function<void(int)> ProgressFunction;
public:
    /// @brief      HTTP POST请求
    /// @param[in]  strUrl 输入参数,请求的Url地址,如:https://www.baidu.com
    /// @param[in]  strParam 输入参数,使用格式”name=kandy&pwd=1234″
    /// @param[out] strResponse 输出参数,返回的内容
    /// @param[in]  pCaPath 输入参数,为CA证书的路径.如果输入为NULL,则不验证服务器端证书的有效性.
    /// @remark     返回是否Post成功
    /// @return     CURLE_OK,成功!其余失败
    int http_post(const string & strUrl, const string & strParam, string & strResponse, const char * pCaPath = NULL);
    /// @brief      HTTPS GET请求
    /// @param[in]  strUrl 输入参数,请求的Url地址,如:https://www.baidu.com
    /// @param[out] strResponse 输出参数,返回的内容
    /// @param[in]  pCaPath 输入参数,为CA证书的路径.如果输入为NULL,则不验证服务器端证书的有效性.
    /// @remark     返回是否Post成功
    /// @return     CURLE_OK,成功!其余失败
    int http_get(const string & strUrl, string & strResponse, const char * pCaPath = NULL);
    /// @brief      文件下载
    /// @param[in]  url : 要下载文件的url地址
    /// @param[in]  outfilename : 下载文件指定的文件名
    /// @remark
    /// @return     返回0代表成功
    int download_file(const string & strUrl, const string & strFile);
    /// @brief      进度报告处理
    /// @param[in]  func : 函数地址
    /// @remark
    /// @return     void
    void set_progress_function(ProgressFunction func);
    /// @brief      进度报告处理
    /// @param[in]  pCallback : 传入的对象
    /// @remark     使用的类继承于IProgressCallback
    /// @return     void
    void set_progress_callback(IProgressCallback *pCallback);
    //
public:
    void SetDebug(bool bDebug);
protected:
    static int progress_callback(void *pParam, double dltotal, double dlnow, double ultotal, double ulnow);
private:
    bool m_bDebug;
    ProgressFunction    m_updateProgress;
    IProgressCallback   *m_pHttpCallback;
};
#endif //__EASY_CURL_H__

EasyCurl.cpp

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <curl/curl.h>
extern “C” {
#include”log.h”
}
#include “EasyCurl.h”
EasyCurl::EasyCurl(void)
: m_bDebug(false)
{
}
EasyCurl::~EasyCurl(void)
{
}
static int OnDebug(CURL *, curl_infotype itype, char * pData, size_t size, void *)
{
    switch(itype){
        case CURLINFO_TEXT:
    Log(“DEBUG %s => %s(): [TEXT], len: %10.10ld bytes (0x%8.8lx), context: \n”, __FILE__, __FUNCTION__, (long)size, (long)size);
            LogHex(pData, size);
            break;
        case CURLINFO_HEADER_IN:
    Log(“DEBUG %s => %s(): [HEADER_IN], len: %10.10ld bytes (0x%8.8lx), context: \n”, __FILE__, __FUNCTION__, (long)size, (long)size);
            LogHex(pData, size);
            break;
        case CURLINFO_HEADER_OUT:
    Log(“DEBUG %s => %s(): [HEADER_OUT], len: %10.10ld bytes (0x%8.8lx), context: \n”, __FILE__, __FUNCTION__, (long)size, (long)size);
            LogHex(pData, size);
            break;
        case CURLINFO_DATA_IN:
    //Log(“DEBUG %s => %s(): [DATA_IN], len: %10.10ld bytes (0x%8.8lx), context: \n”, __FILE__, __FUNCTION__, (long)size, (long)size);
            //LogHex(pData, size);
            break;
        case CURLINFO_DATA_OUT:
    //Log(“DEBUG %s => %s(): [DATA_OUT], len: %10.10ld bytes (0x%8.8lx), context: \n”, __FILE__, __FUNCTION__, (long)size, (long)size);
            //LogHex(pData, size);
            break;
        case CURLINFO_SSL_DATA_IN:
    //Log(“DEBUG %s => %s(): [SSL_DATA_IN], len: %10.10ld bytes (0x%8.8lx), context: \n”, __FILE__, __FUNCTION__, (long)size, (long)size);
            //LogHex(pData, size);
            break;
        case CURLINFO_SSL_DATA_OUT:
    //Log(“DEBUG %s => %s(): [SSL_DATA_OUT], len: %10.10ld bytes (0x%8.8lx), context: \n”, __FILE__, __FUNCTION__, (long)size, (long)size);
            //LogHex(pData, size);
            break;
        default:
    Log(“ERROR %s => %s(): unknown itype: %d, len: %10.10ld bytes (0x%8.8lx), context: \n”, __FILE__, __FUNCTION__, itype, (long)size, (long)size);
            break;
    }
    return 0;
}
static size_t OnWriteData(void* buffer, size_t size, size_t nmemb, void* lpVoid)
{
    string* str = dynamic_cast<string*>((string *)lpVoid);
    if( NULL == str || NULL == buffer ) {
        return -1;
    }
char* pData = (char*)buffer;
str->append(pData, size * nmemb);
Log(“DEBUG %s => %s(): OnWriteData, len: %10.10ld bytes (0x%8.8lx), context: \n”, __FILE__, __FUNCTION__, (long)size*nmemb, (long)size*nmemb);
    LogHex((char *)buffer, size * nmemb);
    return nmemb;
}
static size_t OnReadData(void* buffer, size_t size, size_t nmemb, void* lpVoid)
{
    string* str = dynamic_cast<string*>((string *)lpVoid);
    if( NULL == str || NULL == buffer ) {
        return -1;
    }
char* pData = (char*)buffer;
str->append(pData, size * nmemb);
Log(“DEBUG %s => %s(): OnReadData, len: %10.10ld bytes (0x%8.8lx), context: \n”, __FILE__, __FUNCTION__, (long)size*nmemb, (long)size*nmemb);
    LogHex((char *)buffer, size * nmemb);
    return nmemb;
}
/* libcurl write callback function */
size_t write_data(void *ptr, size_t size, size_t nmemb, FILE *stream)
{
    size_t written = fwrite(ptr, size, nmemb, stream);
    return written;
    //CAN WRITE data to FILE.
    //FILE* fp = NULL;
    //fp = fopen(“c:\\test.dat”, “ab+”);// must be a, otherwise will recovery pre data.
    //size_t nWrite = fwrite(ptr, nSize, nmemb, fp);
    //fclose(fp);
    //return nWrite;
}
//
int EasyCurl::progress_callback(void *pParam, double dltotal, double dlnow, double ultotal, double ulnow)
{
    EasyCurl* pThis = (EasyCurl*)pParam;
    int nPos = (int)((dlnow / dltotal) * 100);
    if (pThis->m_pHttpCallback) {
        pThis->m_pHttpCallback->OnProgressCallback(nPos);
    }
    if (pThis->m_updateProgress) {
        pThis->m_updateProgress(nPos);
    }
    return 0;
}
//
string globalCurlStrSend;
int EasyCurl::http_post(const string & strUrl, const string & strParam, string & strResponse, const char * pCaPath)
{
    CURLcode res;
    CURL* curl = curl_easy_init();
    if(NULL == curl) {
        return CURLE_FAILED_INIT;
    }
    if(m_bDebug) {
        curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);
        curl_easy_setopt(curl, CURLOPT_DEBUGFUNCTION, OnDebug);
    }
    curl_easy_setopt(curl, CURLOPT_URL, strUrl.c_str());
    curl_easy_setopt(curl, CURLOPT_POST, 1L);
    curl_easy_setopt(curl, CURLOPT_POSTFIELDS, strParam.c_str());
    curl_easy_setopt(curl, CURLOPT_READFUNCTION, OnReadData); //not used, only for PUT
    globalCurlStrSend = “”;
    curl_easy_setopt(curl, CURLOPT_READDATA, (void *)&globalCurlStrSend);
    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, OnWriteData);
    curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&strResponse);
    curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L); //for 302, redirect
    curl_easy_setopt(curl, CURLOPT_COOKIEFILE, “”);
    curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1L);
    if(NULL == pCaPath) {
        curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, false); //not verify peer cert and peer host
        curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, false);
    }
    else {
        //default is PEM, so needn’t to set, and can support DER.
        //curl_easy_setopt(curl,CURLOPT_SSLCERTTYPE,”PEM”);
        curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, true);
        curl_easy_setopt(curl, CURLOPT_CAINFO, pCaPath);
    }
    curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 10L); // wait 10 seconds to connect server.
    curl_easy_setopt(curl, CURLOPT_TIMEOUT, 100L); //wait 100 seconds to get content from server.
    res = curl_easy_perform(curl);
    if(res != CURLE_OK){ //CURLE_OK is 0
    Log(“ERROR %s => %s(): curl_easy_perform() failed: %s\n”, __FILE__, __FUNCTION__, curl_easy_strerror(res));
        curl_easy_cleanup(curl);
        return res;
    }
    long retcode = 0;
    res = curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE , &retcode);
    if(res != CURLE_OK){ //CURLE_OK is 0
    Log(“ERROR %s => %s(): curl_easy_getinfo() failed: %s\n”, __FILE__, __FUNCTION__, curl_easy_strerror(res));
        curl_easy_cleanup(curl);
        return res;
    }
    if(retcode == 200 || retcode == 302){ //success
    Log(“DEBUG %s => %s(): curl_easy_getinfo() return code: %ld\n”, __FILE__, __FUNCTION__, retcode);
    }else{ // can return content, but is not wanted content.
    Log(“ERROR %s => %s(): curl_easy_getinfo() return code: %ld\n”, __FILE__, __FUNCTION__, retcode);
        curl_easy_cleanup(curl);
        return -1;
    }
    curl_easy_cleanup(curl);
    return res;
}
//
int EasyCurl::http_get(const string & strUrl, string & strResponse, const char * pCaPath)
{
    CURLcode res;
    CURL* curl = curl_easy_init();
    if(NULL == curl) {
        return CURLE_FAILED_INIT;
    }
    if(m_bDebug) {
        curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);
        curl_easy_setopt(curl, CURLOPT_DEBUGFUNCTION, OnDebug);
    }
    curl_easy_setopt(curl, CURLOPT_URL, strUrl.c_str());
    curl_easy_setopt(curl, CURLOPT_READFUNCTION, OnReadData); //not used, only for PUT
    globalCurlStrSend = “”;
    curl_easy_setopt(curl, CURLOPT_READDATA, (void *)&globalCurlStrSend);
    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, OnWriteData);
    curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&strResponse);
    curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L); //for 302, redirect
    curl_easy_setopt(curl, CURLOPT_COOKIEFILE, “”);
    curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1);
    if(NULL == pCaPath) {
        curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, false); //not verify peer cert and peer host
        curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, false);
    }
    else {
        curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, true);
        curl_easy_setopt(curl, CURLOPT_CAINFO, pCaPath);
    }
    curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 10L);
    curl_easy_setopt(curl, CURLOPT_TIMEOUT, 100L);
    res = curl_easy_perform(curl);
    if(res != CURLE_OK){ //CURLE_OK is 0
    Log(“ERROR %s => %s(): curl_easy_perform() failed: %s\n”, __FILE__, __FUNCTION__, curl_easy_strerror(res));
        curl_easy_cleanup(curl);
        return res;
    }
    long retcode = 0;
    res = curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE , &retcode);
    if(res != CURLE_OK){ //CURLE_OK is 0
    Log(“ERROR %s => %s(): curl_easy_getinfo() failed: %s\n”, __FILE__, __FUNCTION__, curl_easy_strerror(res));
        curl_easy_cleanup(curl);
        return res;
    }
    if(retcode == 200 || retcode == 302){ //success
    Log(“DEBUG %s => %s(): curl_easy_getinfo() return code: %ld\n”, __FILE__, __FUNCTION__, retcode);
    }else{ // can return content, but is not wanted content.
    Log(“ERROR %s => %s(): curl_easy_getinfo() return code: %ld\n”, __FILE__, __FUNCTION__, retcode);
        curl_easy_cleanup(curl);
        return -1;
    }
    curl_easy_cleanup(curl);
    return res;
}
//
int EasyCurl::download_file(const string & strUrl, const string & strFile)
{
    FILE *fp;
    //call curl_easy_init() to get easy interface type pointer.
    CURL *curl = curl_easy_init();
    if (curl) {
        fp = fopen(strFile.c_str(), “wb”);
        CURLcode res = curl_easy_setopt(curl, CURLOPT_URL, strUrl.c_str());
        if (res != CURLE_OK) {
            fclose(fp);
            curl_easy_cleanup(curl);
            return -1;
        }
        res = curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data);
        if (res != CURLE_OK) {
            fclose(fp);
            curl_easy_cleanup(curl);
            return -1;
        }
        res = curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp);
        if (res != CURLE_OK) {
            fclose(fp);
            curl_easy_cleanup(curl);
            return -1;
        }
        curl_easy_setopt(curl, CURLOPT_NOPROGRESS, 0);
        curl_easy_setopt(curl, CURLOPT_PROGRESSFUNCTION, progress_callback);//set progress function.
        curl_easy_setopt(curl, CURLOPT_PROGRESSDATA, this);
        //start to run query.
        res = curl_easy_perform(curl);
        fclose(fp);
        // Check for errors
        if (res != CURLE_OK) {
            curl_easy_cleanup(curl);
            return -1;
        }
        curl_easy_cleanup(curl);// call curl_easy_cleanup() to release memory
    }
    return 0;
}
//
void EasyCurl::set_progress_function(ProgressFunction func)
{
    m_updateProgress = func;
}
//
void EasyCurl::set_progress_callback(IProgressCallback *pCallback)
{
    m_pHttpCallback = pCallback;
}
//
void EasyCurl::SetDebug(bool bDebug)
{
    m_bDebug = bDebug;
}

main.cpp

调用测试:
int main(void)
{
//log init
InitLog();
//loop
EasyCurl easyCurl;
easyCurl.SetDebug(true);
for(;;){
Log(“DEBUG %s => %s(): Enter Main Loop. \n”, __FILE__, __FUNCTION__);
string strUrl = “http://www.baidu.com/”;
string strParam = “id=3435”;
string strResponse = “”; // return content will be saved in this string.
int rtn =easyCurl.http_post(strUrl, strParam, strResponse, NULL);
Log(“DEBUG %s => %s(): http_post return: %d\n”, __FILE__, __FUNCTION__, rtn);
sleep(5);
}
//log uninit
UninitLog();
return0;
}

 

1,964次阅读

Post navigation

前一篇:

Yocto编译杰发或MTK的linux或android时的几个问题

后一篇:

linux下直接写framebuffer(fb0)的方式显示bmp图像

发表回复 取消回复

要发表评论,您必须先登录。

个人介绍

需要么,有事情这里找联系方式:关于天楚锐齿

=== 美女同欣赏,好酒共品尝 ===

微信扫描二维码赞赏该文章:

扫描二维码分享该文章:

分类

  • Linux&Android (81)
  • Uncategorized (1)
  • 下载 (28)
  • 云计算 (38)
  • 人工智能 (9)
  • 大数据 (35)
  • 嵌入式 (34)
  • 杂七杂八 (35)
  • 物联网 (65)
  • 网络 (25)
  • 通信 (22)

归档

近期文章

  • 飞书机器人发送卡片interactive消息
  • Springboot JPA实现对数据库表统一的增删改查
  • WEB的内容安全策略CSP(Content-Security-Policy)
  • CSS利用@media和viewport实现响应式布局自动适配手机电脑等
  • VUE前端增加国际化支持

近期评论

  • linux爱好者 发表在《Linux策略路由及iptables mangle、ip rule、ip route关系及一种Network is unreachable错误》
  • maxshu 发表在《使用Android的HIDL+AIDL方式编写从HAL层到APP层的程序》
  • Ambition 发表在《使用Android的HIDL+AIDL方式编写从HAL层到APP层的程序》
  • Ambition 发表在《使用Android的HIDL+AIDL方式编写从HAL层到APP层的程序》
  • maxshu 发表在《Android9下用ethernet 的Tether模式来做路由器功能》

阅读量

  • 使用Android的HIDL+AIDL方式编写从HAL层到APP层的程序 - 23,708次阅读
  • 卸载深信服Ingress、SecurityDesktop客户端 - 18,404次阅读
  • 车机技术之车规级Linux-Automotive Grade Linux(AGL) - 10,475次阅读
  • linux下的unbound DNS服务器设置详解 - 9,185次阅读
  • 在Android9下用ndk编译vSomeIP和CommonAPI以及使用例子 - 9,074次阅读
  • linux的tee命令导致ssh客户端下的shell卡住不动 - 8,579次阅读
  • Linux策略路由及iptables mangle、ip rule、ip route关系及一种Network is unreachable错误 - 8,070次阅读
  • 车机技术之360°全景影像(环视)系统 - 8,051次阅读
  • 车机技术之Android Automotive - 7,909次阅读
  • Windows下安装QEMU并在qemu上安装ubuntu和debian - 7,792次阅读

其他操作

  • 注册
  • 登录
  • 条目 feed
  • 评论 feed
  • WordPress.org

联系方式

地址
深圳市科技园

时间
周一至周五:  9:00~12:00,14:00~18:00
周六和周日:10:00~12:00

标签

android AT命令 CAN centos docker Hadoop hdfs ip java kickstart linux mapreduce mini6410 modem nova OAuth openstack os python socket ssh uboot 内核 协议 安装 嵌入式 性能 报表 授权 操作系统 数据 数据库 月报 模型 汽车 深信服 源代码 统计 编译 脚本 虚拟机 调制解调器 车机 金融 鉴权
© 2025 天楚锐齿