当前位置: 首页 > news >正文

c用libcurl库实现https下get/post网络通信

一、LibCurl基本编程框架

libcurl是一个跨平台的网络协议库,支持http, https,ftp, gopher, telnet, dict, file, 和ldap 协议。libcurl同样支持HTTPS证书授权,HTTP POST,HTTP PUT, FTP 上传, HTTP基本表单上传,代理,cookies,和用户认证。在基于LibCurl的程序里,主要采用callbackfunction (回调函数)的形式完成传输任务,用户在启动传输前设置好各类参数和回调函数,当满足条件时libcurl将调用用户的回调函数实现特定功能。下面是利用libcurl完成传输任务的流程:

1. 调用curl_global_init()初始化libcurl

2. 调用curl_easy_init()函数得到 easyinterface型指针

3. 调用curl_easy_setopt()设置传输选项

4. 根据curl_easy_setopt()设置的传输选项,实现回调函数以完成用户特定任务

5. 调用curl_easy_perform()函数完成传输任务

6. 调用curl_easy_cleanup()释放内存

在整过过程中设置curl_easy_setopt()参数是最关键的,几乎所有的libcurl程序都要使用它。

二、一些基本的函数

1.CURLcode curl_global_init(long flags);

描述:

这个函数只能用一次。(其实在调用curl_global_cleanup函数后仍然可再用)

如果这个函数在curl_easy_init函数调用时还没调用,它讲由libcurl库自动调用,所以多线程下最好主动调用该函数以防止在线程中curl_easy_init时多次调用。

注意:虽然libcurl是线程安全的,但curl_global_init是不能保证线程安全的,所以不要在每个线程中都调用curl_global_init,应该将该函数的调用放在主线程中。

参数:flags

CURL_GLOBAL_ALL //初始化所有的可能的调用。

CURL_GLOBAL_SSL //初始化支持安全套接字层。

CURL_GLOBAL_WIN32 //初始化win32套接字库。

CURL_GLOBAL_NOTHING//没有额外的初始化。

2 void curl_global_cleanup(void);

描述:在结束libcurl使用的时候,用来对curl_global_init做的工作清理。类似于close的函数。

注意:虽然libcurl是线程安全的,但curl_global_cleanup是不能保证线程安全的,所以不要在每个线程中都调用curl_global_init,应该将该函数的调用放在主线程中。

3 char *curl_version( );

描述: 打印当前libcurl库的版本。

4 CURL *curl_easy_init( );

描述:

curl_easy_init用来初始化一个CURL的指针(有些像返回FILE类型的指针一样). 相应的在调用结束时要用curl_easy_cleanup函数清理.

一般curl_easy_init意味着一个会话的开始. 它会返回一个easy_handle(CURL*对象), 一般都用在easy系列的函数中.

5 void curl_easy_cleanup(CURL *handle);

描述:

这个调用用来结束一个会话.与curl_easy_init配合着用. 

参数:

CURL类型的指针.

6 CURLcode curl_easy_setopt(CURL *handle, CURLoption option,parameter);

描述: 这个函数最重要了.几乎所有的curl 程序都要频繁的使用它.它告诉curl库.程序将有如何的行为. 比如要查看一个网页的html代码等.(这个函数有些像ioctl函数)参数:

1 CURL类型的指针

2 各种CURLoption类型的选项.(都在curl.h库里有定义,man 也可以查看到)

3 parameter 这个参数既可以是个函数的指针,也可以是某个对象的指针,也可以是个long型的变量.它用什么这取决于第二个参数.

CURLoption 这个参数的取值很多.具体的可以查看man手册.

7 CURLcode curl_easy_perform(CURL *handle);

描述:这个函数在初始化CURL类型的指针以及curl_easy_setopt完成后调用. 就像字面的意思所说perform就像是个舞台.让我们设置的

option 运作起来.参数:

CURL类型的指针.

三、curl_easy_setopt函数部分选项介绍

本节主要介绍curl_easy_setopt中跟http相关的参数。该函数是curl中非常重要的函数,curl所有设置都是在该函数中完成的,该函数的设置选项众多,注意本节的阐述的只是部分常见选项。

1. CURLOPT_URL 

设置访问URL

2. CURLOPT_WRITEFUNCTION,CURLOPT_WRITEDATA

回调函数原型为:size_t function(void *ptr, size_t size, size_t nmemb, void *stream);函数将在libcurl接收到数据后被调用,因此函数多做数据保存的功能,如处理下载文件。CURLOPT_WRITEDATA用于表明CURLOPT_WRITEFUNCTION函数中的stream指针的来源。

如果你没有通过CURLOPT_WRITEFUNCTION属性给easy handle设置回调函数,libcurl会提供一个默认的回调函数,它只是简单的将接收到的数据打印到标准输出。你也可以通过CURLOPT_WRITEDATA属性给默认回调函数传递一个已经打开的文件指针,用于将数据输出到文件里。

3. CURLOPT_HEADERFUNCTION,CURLOPT_HEADERDATA

回调函数原型为 size_tfunction( void *ptr, size_t size,size_t nmemb, void *stream); libcurl一旦接收到http 头部数据后将调用该函数。CURLOPT_WRITEDATA传递指针给libcurl,该指针表明CURLOPT_HEADERFUNCTION函数的stream指针的来源。

4. CURLOPT_READFUNCTIONCURLOPT_READDATA

libCurl需要读取数据传递给远程主机时将调用CURLOPT_READFUNCTION指定的函数,函数原型是:size_tfunction(void *ptr, size_t size, size_t nmemb,void *stream). CURLOPT_READDATA 表明CURLOPT_READFUNCTION函数原型中的stream指针来源。

5. CURLOPT_NOPROGRESS,CURLOPT_PROGRESSFUNCTION,CURLOPT_PROGRESSDATA

跟数据传输进度相关的参数。CURLOPT_PROGRESSFUNCTION指定的函数正常情况下每秒被libcurl调用一次,为了使CURLOPT_PROGRESSFUNCTION被调用,CURLOPT_NOPROGRESS必须被设置为false,CURLOPT_PROGRESSDATA指定的参数将作为CURLOPT_PROGRESSFUNCTION指定函数的第一个参数

6. CURLOPT_TIMEOUT,CURLOPT_CONNECTIONTIMEOUT:

CURLOPT_TIMEOUT 由于设置传输时间,CURLOPT_CONNECTIONTIMEOUT 设置连接等待时间

7. CURLOPT_FOLLOWLOCATION

设置重定位URL

8.CURLOPT_RANGE: CURLOPT_RESUME_FROM:

断点续传相关设置。CURLOPT_RANGE指定char *参数传递给libcurl,用于指明http域的RANGE头域,例如:

表示头500个字节:bytes=0-499

表示第二个500字节:bytes=500-999

表示最后500个字节:bytes=-500

表示500字节以后的范围:bytes=500-

第一个和最后一个字节:bytes=0-0,-1

同时指定几个范围:bytes=500-600,601-999

CURLOPT_RESUME_FROM 传递一个long参数给libcurl,指定你希望开始传递的偏移量。

四、curl_easy_perform函数说明(error 状态码)

该函数是完成curl_easy_setopt指定的所有选项,本节重点介绍curl_easy_perform的返回值。返回0意味一切ok,非0代表错误发生。主要错误码说明:

1. CURLE_OK 

任务完成一切都好

2 CURLE_UNSUPPORTED_PROTOCOL

不支持的协议,由URL的头部指定

3 CURLE_COULDNT_CONNECT

不能连接到remote 主机或者代理

4 CURLE_REMOTE_ACCESS_DENIED

访问被拒绝

5 CURLE_HTTP_RETURNED_ERROR

Http返回错误

6 CURLE_READ_ERROR

读本地文件错误

要获取详细的错误描述字符串,可以通过const char*curl_easy_strerror(CURLcode errornum )这个函数取得.

五、http与https的区别

Http是明文发送,任何人都可以拦截并读取内容

Https是加密传输协议,用它传输的内容都是加密过的,https是http的扩展,其安全基础是SSL协议 #协议层理解,多了一层对数据的加密,加密方式是SSL加密,应该是公钥和私钥的理解。

###################################################

POST:

###################################################

#include <stdio.h>

#include <stdlib.h>

#include <string.h>

#include <curl/curl.h>


int main(void)

{

CURL *curl;

CURLcode res;

curl_global_init(CURL_GLOBAL_ALL);

/* get a curl handle */

curl = curl_easy_init();

if (!curl) {

return -1;

}

/*设置easy handle属性*/

/* specify URL */

curl_easy_setopt(curl, CURLOPT_URL, url);

/* specify we want to POST data */

curl_easy_setopt(curl, CURLOPT_POST, 1L);

/* Set the expected POST size */

curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, (long)datelen);

/* Set the expected POST data */

curl_easy_setopt(curl,CURLOPT_POSTFIELDS, (char *)postdata);

curl_easy_setopt (curl,CURLOPT_SSL_VERIFYPEER, 0L);

curl_easy_setopt (curl,CURLOPT_SSL_VERIFYHOST, 0L);

curl_easy_setopt (curl,CURLOPT_SSLCERT,"client.crt");

curl_easy_setopt (curl, CURLOPT_SSLCERTTYPE, "PEM");

curl_easy_setopt (curl, CURLOPT_SSLKEY,"client.key");

curl_easy_setopt (curl, CURLOPT_SSLKEYTYPE,"PEM");

curl_easy_setopt (curl,CURLOPT_TIMEOUT, 60L);

curl_easy_setopt (curl,CURLOPT_CONNECTTIMEOUT, 10L);

 

/*执行数据请求*/

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);

curl_global_cleanup();

return 0;

}

###################################################

GET:

###################################################

#include <stdio.h>

#include <stdlib.h>

#include <string.h>

#include <curl/curl.h>


struct MemoryStruct {

  char *memory;

  size_t size;

};

 

static size_t

WriteMemoryCallback(void *contents, size_t size, size_t nmemb, void *userp)

{

  size_t realsize = size * nmemb;

  struct MemoryStruct *mem = (struct MemoryStruct *)userp;

 

  mem->memory = realloc(mem->memory, mem->size + realsize + 1);

  if(mem->memory == NULL) {

    /* out of memory! */ 

    printf("not enough memory (realloc returned NULL)\n");

    return 0;

  }

 

  memcpy(&(mem->memory[mem->size]), contents, realsize);

  mem->size += realsize;

  mem->memory[mem->size] = 0;

 

  return realsize;

}


int main(void)

{

CURL *curl = NULL;

CURLcode res;

struct MemoryStruct chunk;


chunk.memory = malloc(1);  /* will be grown as needed by the realloc above */ 

chunk.size = 0;    /* no data at this point */ 

curl_global_init(CURL_GLOBAL_ALL);

/* get a curl handle */

curl = curl_easy_init();

if (!curl) {

return -1;

}

 

/*设置easy handle属性*/

/* specify URL */

curl_easy_setopt (curl,CURLOPT_URL, url);

/* Define our callback to get called when there's data to be written */

curl_easy_setopt (curl,CURLOPT_WRITEFUNCTION, WriteMemoryCallback);

/* Set a pointer to our struct to pass to the callback */

curl_easy_setopt(curl,CURLOPT_WRITEDATA, (void *)&chunk);

/* set commom option */

curl_easy_setopt (curl,CURLOPT_SSL_VERIFYPEER, 0L);

curl_easy_setopt (curl,CURLOPT_SSL_VERIFYHOST, 0L);

curl_easy_setopt (curl,CURLOPT_SSLCERT,"client.crt");

curl_easy_setopt (curl, CURLOPT_SSLCERTTYPE, "PEM");

curl_easy_setopt (curl, CURLOPT_SSLKEY,"client.key");

curl_easy_setopt (curl, CURLOPT_SSLKEYTYPE,"PEM");

curl_easy_setopt (curl,CURLOPT_TIMEOUT, 60L);

curl_easy_setopt (curl,CURLOPT_CONNECTTIMEOUT, 10L);

/* get verbose debug output please */

 

/*执行数据请求*/

res = curl_easy_perform(curl);

if (res !=CURLE_OK) {

fprintf(stderr, "curl_easy_perform() failed: %s\n",

curl_easy_strerror(res));

}   

// 释放资源

free(chunk.memory);

curl_easy_cleanup(curl);

curl_global_cleanup();

return 0;

}

###################################################

上传文件:

###################################################

#include <stdio.h>

#include <stdlib.h>

#include <string.h>

#include <curl/curl.h>


//这个函数是为了符合CURLOPT_READFUNCTION而构造的

//数据上传时使用

static size_t read_callback(void *ptr, size_t size, size_t nmemb, void *stream)

{

  size_t retcode;

  curl_off_t nread;

 

  /* in real-world cases, this would probably get this data differently

     as this fread() stuff is exactly what the library already would do

     by default internally */ 

  retcode = fread(ptr, size, nmemb, stream);

 

  nread = (curl_off_t)retcode;

 

  fprintf(stderr, "*** We read %" CURL_FORMAT_CURL_OFF_T

          " bytes from file\n", nread);

 

  return retcode;

}


int main(void)

{

CURL *curl;

CURLcode res;

FILE * fstream;

struct stat file_info;


/* get the file size of the local file */ 

stat(file, &file_info);

fstream = fopen(file, "rb");

curl_global_init(CURL_GLOBAL_ALL);

/* get a curl handle */

curl = curl_easy_init();

if (!curl) {

return -1;

}

/*设置easy handle属性*/

/* specify URL */

curl_easy_setopt(curl, CURLOPT_URL, url);

/* we want to use our own read function */

curl_easy_setopt(curl, CURLOPT_READFUNCTION, read_callback);

/* which file to upload */

curl_easy_setopt(curl, CURLOPT_READDATA, (void *) fstream);

/* enable "uploading" */

curl_easy_setopt(curl, CURLOPT_UPLOAD, 1L);

/* Set the size of the file to upload (optional) */

curl_easy_setopt(curl,CURLOPT_INFILESIZE_LARGE, (curl_off_t)file_info.st_size);

/* set commom option */

curl_easy_setopt (curl,CURLOPT_SSL_VERIFYPEER, 0L);

curl_easy_setopt (curl,CURLOPT_SSL_VERIFYHOST, 0L);

curl_easy_setopt (curl,CURLOPT_SSLCERT,"client.crt");

curl_easy_setopt (curl, CURLOPT_SSLCERTTYPE, "PEM");

curl_easy_setopt (curl, CURLOPT_SSLKEY,"client.key");

curl_easy_setopt (curl, CURLOPT_SSLKEYTYPE,"PEM");

curl_easy_setopt (curl,CURLOPT_TIMEOUT, 60L);

curl_easy_setopt (curl,CURLOPT_CONNECTTIMEOUT, 10L);

/* get verbose debug output please */

 

  /*执行数据请求*/

res = curl_easy_perform(curl);

if (res !=CURLE_OK) {

fprintf(stderr, "curl_easy_perform() failed: %s\n",

 curl_easy_strerror(res));

}   

// 释放资源

if(fstream)

fclose(fstream);

curl_easy_cleanup(curl);

curl_global_cleanup();

return 0;

}

#########################################################

下载文件:

###################################################

#include <stdio.h>

#include <stdlib.h>

#include <string.h>

#include <curl/curl.h>


这个函数是为了符合CURLOPT_WRITEFUNCTION而构造的

//完成数据保存功能

struct FtpFile {

  const char *filename;

  FILE *stream;

};

 

static size_t my_fwrite(void *buffer, size_t size, size_t nmemb, void *stream)

{

  struct FtpFile *out = (struct FtpFile *)stream;

  if(out && !out->stream) {

    /* open file for writing */ 

    out->stream = fopen(out->filename, "wb");

    if(!out->stream)

      return -1; /* failure, can't open file to write */ 

  }

  return fwrite(buffer, size, nmemb, out->stream);

}


int main(void)

{

CURL *curl;

CURLcode res;

struct FtpFile ftpfile;

curl_global_init(CURL_GLOBAL_ALL);

/* get a curl handle */

curl = curl_easy_init();

if (!curl) {

return -1;

}

 

/*设置easy handle属性*/

/* specify URL */

curl_easy_setopt(curl, CURLOPT_URL, url);

/* Define our callback to get called when there's data to be written */

curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, my_fwrite);

/* Set a pointer to our struct to pass to the callback */

curl_easy_setopt(curl,CURLOPT_WRITEDATA, &ftpfile);

/* set commomoption */

curl_easy_setopt (curl,CURLOPT_SSL_VERIFYPEER, 0L);

curl_easy_setopt (curl,CURLOPT_SSL_VERIFYHOST, 0L);

curl_easy_setopt (curl,CURLOPT_SSLCERT,"client.crt");

curl_easy_setopt (curl, CURLOPT_SSLCERTTYPE, "PEM");

curl_easy_setopt (curl, CURLOPT_SSLKEY,"client.key");

curl_easy_setopt (curl, CURLOPT_SSLKEYTYPE,"PEM");

curl_easy_setopt (curl,CURLOPT_TIMEOUT, 60L);

curl_easy_setopt (curl,CURLOPT_CONNECTTIMEOUT, 10L);

/* get verbose debug output please */

 

 /*执行数据请求*/

res = curl_easy_perform(curl);

if (res !=CURLE_OK) {

fprintf(stderr, "curl_easy_perform() failed: %s\n",

curl_easy_strerror(res));

}   

// 释放资源

if(ftpfile.stream)

fclose(ftpfile.stream); /* close the local file */ 

curl_easy_cleanup(curl);

curl_global_cleanup();


return 0;

}

参考:https://curl.haxx.se/libcurl/

参考:http://blog.csdn.net/wangqing_12345/article/details/52211287



本文转自 Linux_woniu 51CTO博客,原文链接:http://blog.51cto.com/linuxcgi/1968194

相关文章:

  • bootstrap标题效果
  • nmap的用法
  • java 二叉树 深度优先递归遍历
  • 基于nginx部署app下载服务器
  • itunes Connect 未能创建 App 图标
  • Exchange(2007/2010/2013)共存环境中IMAP和POP的工作方式
  • 第二章 索引
  • 金山词霸PDF文档取词
  • 如何使用OpenSSL自签证书(Self-Sign Certificate)
  • 为什么,博主我要写下这一系列windows实用网络?
  • CentOS系统中出现错误--SSH:connect to host centos-py port 22: Connection refused
  • 笔记本外接显示器切换失败原因
  • 用路由标记过滤路由更新
  • 简单干净的C#方法设计案例:SFCUI.AjaxValue()之三
  • 各版本最新的Visual C++可再发行组件包(Redistributable Package)下载和合集
  • [译]Python中的类属性与实例属性的区别
  • create-react-app做的留言板
  • happypack两次报错的问题
  • HTTP--网络协议分层,http历史(二)
  • JavaScript设计模式之工厂模式
  • Java到底能干嘛?
  • JS学习笔记——闭包
  • React-redux的原理以及使用
  • ViewService——一种保证客户端与服务端同步的方法
  • Webpack4 学习笔记 - 01:webpack的安装和简单配置
  • windows下mongoDB的环境配置
  • 从零开始的webpack生活-0x009:FilesLoader装载文件
  • 记一次删除Git记录中的大文件的过程
  • 技术发展面试
  • 解决jsp引用其他项目时出现的 cannot be resolved to a type错误
  • 批量截取pdf文件
  • 普通函数和构造函数的区别
  • 通过来模仿稀土掘金个人页面的布局来学习使用CoordinatorLayout
  • 7行Python代码的人脸识别
  • 宾利慕尚创始人典藏版国内首秀,2025年前实现全系车型电动化 | 2019上海车展 ...
  • ​【原创】基于SSM的酒店预约管理系统(酒店管理系统毕业设计)
  • ​LeetCode解法汇总2182. 构造限制重复的字符串
  • ​软考-高级-系统架构设计师教程(清华第2版)【第20章 系统架构设计师论文写作要点(P717~728)-思维导图】​
  • # 飞书APP集成平台-数字化落地
  • # 日期待t_最值得等的SUV奥迪Q9:空间比MPV还大,或搭4.0T,香
  • #100天计划# 2013年9月29日
  • #include
  • (Spark3.2.0)Spark SQL 初探: 使用大数据分析2000万KF数据
  • (安全基本功)磁盘MBR,分区表,活动分区,引导扇区。。。详解与区别
  • (六)Hibernate的二级缓存
  • (转)【Hibernate总结系列】使用举例
  • (转)3D模板阴影原理
  • (转)C#开发微信门户及应用(1)--开始使用微信接口
  • (转)Scala的“=”符号简介
  • ***利用Ms05002溢出找“肉鸡
  • . ./ bash dash source 这五种执行shell脚本方式 区别
  • .NET Core6.0 MVC+layui+SqlSugar 简单增删改查
  • .net通用权限框架B/S (三)--MODEL层(2)
  • .NET性能优化(文摘)
  • /usr/bin/python: can't decompress data; zlib not available 的异常处理