简介
大多数在linux下的开发者,都会用到curl这个命令行工具。对于进行restful api的测试等,非常方便。其实,这个工具还提供了一个C的开发库,可以很方便的在C语言开发环境下完成基于http的请求和响应交互,高效的开发基于http/smtp等的网络应用程序
/* 2023-08-14 更新宏定义
1. 使用可变参数,支持多项输出;
2. 去除Z中默认加上的双引号;
*/
#define X_LOG_DEBUG(Z, X...) \
printf("[%s %s] [%s.%d] [%s] [DEBUG] " Z "\n", __DATE__, __TIME__, __FILE__, __LINE__, __FUNCTION__, ##X)
环境准备
下载并安装curl的开发包
yum install libcurl-devel.x86_64
在线资源
开发过程中主要参考CURL官方介绍及API参考文档 | link
示例代码
多余的话就不多说了,直接上示例代码,通过代码中的注释来说明开发过程。
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "../include/xhttp.h"
/*
- 这个是一个回调函数,主要用于curl在执行过程中,当有被请求的数据到达时,被调用来向-curl_easy_setopt设置的chunk中写入数据。
这个回调函数在curl_easy_perform执行完成前会被调用多次。当执行完成后,从chunk中取出这次交互返回的数据。
*/
static size_t cb_write_data(void *data, size_t size, size_t nmemb, void *clientp)
{
size_t realsize = size * nmemb;
http_response *mem = (http_response *)clientp;
char *ptr = realloc(mem->response, mem->size + realsize + 1);
if(ptr == NULL)
return 0; /* out of response_st! */
mem->response = ptr;
memcpy(&(mem->response[mem->size]), data, realsize);
mem->size += realsize;
mem->response[mem->size] = 0;
return realsize;
}
/*
这个是向外发布的一个函数,调用的方式示例如下:
char* payload = "{\"code\":\"\",\"codeUuid\":\"\",\"loginName\":\"user@domain\",\"loginPwd\":\"xxxxxxxx\"}";
http_response *resp = http_post("https://local.domain/admin-api/session/login", NULL, payload);
使用完返回数据后,记得释放resp->reesponse,避免内存漏。
*/
http_response* http_post(char* url, char* token, char* payload)

本文介绍了如何在C语言中利用libcurl库进行HTTPGET和POST请求的开发,包括环境配置、示例代码展示以及回调函数的使用,以创建基于HTTP的网络应用程序。
最低0.47元/天 解锁文章
1万+

被折叠的 条评论
为什么被折叠?



