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

curl封装

一。由于工作的原因,需要对curl做一些封装,附加上我们的证书,提供给第三个C++和jAVA使用。

二。头文件封闭四个函数,get,post,download,upload

#ifndef CURLHTTP_H
#define CURLHTTP_H#include <iostream>
#include <string>
#include <curl/curl.h>class CurlHttp {
public:
CurlHttp();
~CurlHttp();CURLcode get(const std::string& url, std::string& response);
CURLcode post(const std::string& url, const std::string& data, std::string& response);
CURLcode download(const std::string& url, const std::string& savePath);
CURLcode upload(const std::string& url, const std::string& filePath, std::string& response);
private:
CURL* curl;static size_t WriteCallback(void* contents, size_t size, size_t nmemb, std::string* response);
void setSSLSettings();
};#endif // CURLHTTP_H

三。实现Cpp,返回一个CURLcode方便出错时追踪错误

#include "CurlHttp.h"CurlHttp::CurlHttp() {curl = curl_easy_init();if (!curl) {std::cerr << "Failed to initialize cURL" << std::endl;}
}CurlHttp::~CurlHttp() {if (curl) {curl_easy_cleanup(curl);}
}CURLcode CurlHttp::get(const std::string& url, std::string& response) {CURLcode res = CURLE_FAILED_INIT;if (curl) {curl_easy_setopt(curl, CURLOPT_URL, url.c_str());curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response);setSSLSettings();res = curl_easy_perform(curl);if (res != CURLE_OK) {std::cerr << "cURL GET request failed: " << curl_easy_strerror(res) << std::endl;}}return res;
}CURLcode CurlHttp::post(const std::string& url, const std::string& data, std::string& response) {CURLcode res = CURLE_FAILED_INIT;if (curl) {curl_easy_setopt(curl, CURLOPT_URL, url.c_str());curl_easy_setopt(curl, CURLOPT_POSTFIELDS, data.c_str());curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response);setSSLSettings();// 设置请求头为JSON类型struct curl_slist* headers = nullptr;headers = curl_slist_append(headers, "Content-Type: application/json");curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);res = curl_easy_perform(curl);if (res != CURLE_OK) {std::cerr << "cURL POST request failed: " << curl_easy_strerror(res) << std::endl;}}return res;
}CURLcode CurlHttp::download(const std::string& url, const std::string& savePath) {CURLcode res = CURLE_FAILED_INIT;if (curl) {FILE* file = fopen(savePath.c_str(), "wb");if (file) {curl_easy_setopt(curl, CURLOPT_URL, url.c_str());curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, NULL);curl_easy_setopt(curl, CURLOPT_WRITEDATA, file);setSSLSettings();res = curl_easy_perform(curl);if (res != CURLE_OK) {std::cerr << "cURL download failed: " << curl_easy_strerror(res) << std::endl;}fclose(file);} else {std::cerr << "Failed to open file for writing: " << savePath << std::endl;res = CURLE_FAILED_INIT;}}return res;
}CURLcode CurlHttp::upload(const std::string& url, const std::string& filePath, std::string& response) {CURLcode res = CURLE_FAILED_INIT;if (curl) {FILE* file = fopen(filePath.c_str(), "rb");if (file) {curl_easy_setopt(curl, CURLOPT_URL, url.c_str());curl_easy_setopt(curl, CURLOPT_UPLOAD, 1L);curl_easy_setopt(curl, CURLOPT_READDATA, file);curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response);setSSLSettings();res = curl_easy_perform(curl);if (res != CURLE_OK) {std::cerr << "cURL upload failed: " << curl_easy_strerror(res) << std::endl;}fclose(file);} else {std::cerr << "Failed to open file for reading: " << filePath << std::endl;res = CURLE_FAILED_INIT;}}return res;
}size_t CurlHttp::WriteCallback(void* contents, size_t size, size_t nmemb, std::string* response) {size_t total_size = size * nmemb;//response->append((char*)contents, total_size);response->append(static_cast<char*>(contents), totalSize);return total_size;
}void CurlHttp::setSSLSettings() {// 设置证书路径curl_easy_setopt(curl, CURLOPT_CAINFO, "/path/to/certificate.pem");// 设置私钥路径curl_easy_setopt(curl, CURLOPT_SSLKEY, "/path/to/private.key");// 设置私钥密码(如果有的话)curl_easy_setopt(curl, CURLOPT_KEYPASSWD, "password");
}

四。测试函数:

#include <iostream>
#include "CurlHttp.h"int main() {CurlHttp curlHttp;// 发起 GET 请求std::string url = "https://api.example.com/data";std::string response;CURLcode res = curlHttp.get(url, response);if (res == CURLE_OK) {std::cout << "GET request successful. Response: " << response << std::endl;} else {std::cerr << "GET request failed. Error: " << curl_easy_strerror(res) << std::endl;}// 发起 POST 请求url = "https://api.example.com/post";std::string data = "key1=value1&key2=value2";response.clear();res = curlHttp.post(url, data, response);if (res == CURLE_OK) {std::cout << "POST request successful. Response: " << response << std::endl;} else {std::cerr << "POST request failed. Error: " << curl_easy_strerror(res) << std::endl;}// 下载文件url = "https://example.com/file.jpg";std::string savePath = "/path/to/save/file.jpg";res = curlHttp.download(url, savePath);if (res == CURLE_OK) {std::cout << "File downloaded successfully and saved at: " << savePath << std::endl;} else {std::cerr << "File download failed. Error: " << curl_easy_strerror(res) << std::endl;}// 上传文件url = "https://api.example.com/upload";std::string filePath = "/path/to/upload/file.txt";response.clear();res = curlHttp.upload(url, filePath, response);if (res == CURLE_OK) {std::cout << "File uploaded successfully. Response: " << response << std::endl;} else {std::cerr << "File upload failed. Error: " << curl_easy_strerror(res) << std::endl;}return 0;
}

六。创建一个aidl文件

package com.example.yourpackage; // 替换为您的包名interface ICurlHttpService {int get(in String url, out String response);int post(in String url, in String data, out String response);int download(in String url, in String savePath);int upload(in String url, in String filePath, out String response);
}

http://www.lryc.cn/news/142484.html

相关文章:

  • C语言数据类型和变量
  • 分布式训练 最小化部署docker swarm + docker-compose落地方案
  • QT学习笔记-开发环境编译Qt MySql数据库驱动与交叉编译Qt MySql数据库驱动
  • QT使用QXlsx实现数据验证与Excel公式操作 QT基础入门【Excel的操作】
  • renrenfast Vue2 打包发布
  • NoSQL数据库介绍+Redis部署
  • 【mindspore学习】环境配置
  • 基于shell脚本对aliyun npm仓库(https://packages.aliyun.com)登录认证
  • K8s Pod 安全认知:从openshift SCC 到 PSP 弃用以及现在的 PSA
  • 提高企业会计效率,选择Manager for Mac(企业会计软件)
  • 软考:中级软件设计师:信息系统的安全属性,对称加密和非对称加密,信息摘要,数字签名技术,数字信封与PGP
  • Vue3中reactive响应式失效的问题
  • lamp
  • LeetCode 周赛上分之旅 #42 当 LeetCode 考树上倍增,出题的趋势在变化吗
  • Qt 自定义菜单 托盘菜单
  • channel并发编程
  • 苹果新健康专利:利用 iPhone、Apple Watch 来分析佩戴者的呼吸情况
  • 数据分析基础-数据可视化02-不同数据类型的可视化概念及原则
  • QT项目使用Qss的总结
  • suricata初体验+wireshark流量分析
  • 机器学习:异常检测实战
  • 数据结构1
  • 自然语言处理学习笔记(七)————字典树效率改进
  • forEach和map有什么区别,使用场景?
  • 【Spring Boot】SpringBoot完整实现社交网站系统
  • Modbus转Profinet网关连接三菱变频器博图快速配置
  • 8.9 【C语言】有关指针的小结
  • WordPress Nginx伪静态规则设置以及二级目录规则
  • 2023年高教社杯 国赛数学建模思路 - 复盘:人力资源安排的最优化模型
  • React内置函数之startTransition与useTransition