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

武汉做营销型网站建设国际军事新闻最新消息视频

武汉做营销型网站建设,国际军事新闻最新消息视频,网站优化 seo和sem,做抽纸行业网站在现代软件开发中,与外部API服务进行通信已成为常见需求。本文将展示如何使用C和libcurl库实现基本的HTTP请求,包括GET请求、POST请求(带JSON数据)以及包含文件上传的POST请求。 准备工作 首先,需要确保已安装libcur…

在现代软件开发中,与外部API服务进行通信已成为常见需求。本文将展示如何使用C++和libcurl库实现基本的HTTP请求,包括GET请求、POST请求(带JSON数据)以及包含文件上传的POST请求。

准备工作

首先,需要确保已安装libcurl库,并正确链接到项目中。如果还没有安装libcurl,可以在libcurl官网找到安装方法。使用CMake构建项目时,可以在CMakeLists.txt中指定库路径,确保CURL能够找到:

# set(CMAKE_PREFIX_PATH "${CMAKE_SOURCE_DIR}/libcurl/share/curl")  # 替换为 CURL 安装的实际路径
find_package(CURL REQUIRED)
target_link_libraries(your_project_name PRIVATE CURL::libcurl)

基本结构

代码的核心是三个函数,分别用于GET请求、带JSON的POST请求和包含文件上传的POST请求。每个函数使用了libcurl的不同配置来处理具体需求。

代码结构和功能实现

1. req_reply:处理请求响应的函数

这个函数是libcurl的回调函数,用于处理从服务器返回的数据,将数据写入到指定的字符串流中。

size_t req_reply(void *ptr, size_t size, size_t nmemb, void *stream) {string *str = (string *) stream;(*str).append((char *) ptr, size * nmemb);return size * nmemb;
}
2. GET 请求

GET请求是最常用的请求类型,用于从服务器获取资源。curl_get_req函数实现了GET请求,通过curl_easy_setopt函数来设置URL和请求参数。

CURLcode curl_get_req(const std::string &url, std::string &response) {CURL *curl = curl_easy_init();CURLcode res;if (curl) {curl_easy_setopt(curl, CURLOPT_URL, url.c_str());curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, false);  // 忽略SSL证书验证curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, false);curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, req_reply);curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *) &response);curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 3);curl_easy_setopt(curl, CURLOPT_TIMEOUT, 3);res = curl_easy_perform(curl);curl_easy_cleanup(curl);}return res;
}
3. 发送带JSON数据的POST请求

POST请求通常用于将数据发送到服务器,尤其是RESTful API。curl_post_json函数可以发送包含JSON数据的POST请求,代码通过设置Content-Type头为application/json来指定数据类型。

CURLcode curl_post_json(const string &url, const string &jsonData, string &response) {CURL *curl = curl_easy_init();CURLcode res;if (curl) {struct curl_slist *headers = NULL;headers = curl_slist_append(headers, "Content-Type: application/json");curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);curl_easy_setopt(curl, CURLOPT_POST, 1);curl_easy_setopt(curl, CURLOPT_URL, url.c_str());curl_easy_setopt(curl, CURLOPT_POSTFIELDS, jsonData.c_str());curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, req_reply);curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *) &response);res = curl_easy_perform(curl);curl_slist_free_all(headers);curl_easy_cleanup(curl);}return res;
}
4. 发送包含JSON和文件的POST请求

在某些情况下,我们可能需要同时发送JSON数据和文件。这里用curl_mime实现多部分表单上传。curl_mime允许将JSON数据和文件字段一起打包并发送给服务器。

CURLcode curl_post_with_file(const string &url, const string &jsonData, const string &filePath, string &response) {CURL *curl = curl_easy_init();CURLcode res;if (curl) {struct curl_slist *headers = NULL;headers = curl_slist_append(headers, "Content-Type: multipart/form-data");curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);// 创建 MIME 表单curl_mime *form = curl_mime_init(curl);// 添加 JSON 数据字段curl_mimepart *jsonField = curl_mime_addpart(form);curl_mime_name(jsonField, "json");curl_mime_data(jsonField, jsonData.c_str(), CURL_ZERO_TERMINATED);curl_mime_type(jsonField, "application/json");// 添加文件字段curl_mimepart *fileField = curl_mime_addpart(form);curl_mime_name(fileField, "file");curl_mime_filedata(fileField, filePath.c_str());curl_mime_type(fileField, "image/png");curl_easy_setopt(curl, CURLOPT_URL, url.c_str());curl_easy_setopt(curl, CURLOPT_MIMEPOST, form);curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, req_reply);curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *) &response);res = curl_easy_perform(curl);curl_mime_free(form);curl_slist_free_all(headers);curl_easy_cleanup(curl);}return res;
}

测试用例

最后,我们在main函数中展示了三个测试用例,分别是GET请求、带JSON数据的POST请求和带文件的POST请求。

#include <iostream>
#include <string>
#include "curl/curl.h"using namespace std;// 请求的回复处理函数
size_t req_reply(void *ptr, size_t size, size_t nmemb, void *stream) {string *str = (string *) stream;(*str).append((char *) ptr, size * nmemb);return size * nmemb;
}// HTTP GET 请求
CURLcode curl_get_req(const std::string &url, std::string &response) {CURL *curl = curl_easy_init();CURLcode res;if (curl) {// 设置 URL 地址curl_easy_setopt(curl, CURLOPT_URL, url.c_str());// 设置忽略 SSL 证书验证curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, false);curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, false);curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);// 设置回复处理函数curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, req_reply);curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *) &response);curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1);curl_easy_setopt(curl, CURLOPT_HEADER, 1);// 设置连接和响应超时时间curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 3);curl_easy_setopt(curl, CURLOPT_TIMEOUT, 3);res = curl_easy_perform(curl);  // 执行 GET 请求curl_easy_cleanup(curl);  // 清理 curl 资源}return res;
}// 发送带有 JSON 数据的 HTTP POST 请求
CURLcode curl_post_json(const string &url, const string &jsonData, string &response) {CURL *curl = curl_easy_init();CURLcode res;if (curl) {struct curl_slist *headers = NULL;headers = curl_slist_append(headers, "Content-Type: application/json"); // 设置 JSON 类型头部//    headers = curl_slist_append(headers, ("appcode: " + appcode).c_str());//    headers = curl_slist_append(headers, ("User-Agent: " + agent).c_str());curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);// 设置 POST 请求参数curl_easy_setopt(curl, CURLOPT_POST, 1);curl_easy_setopt(curl, CURLOPT_URL, url.c_str());curl_easy_setopt(curl, CURLOPT_POSTFIELDS, jsonData.c_str());curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, false);curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, false);curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, req_reply);curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *) &response);curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1);curl_easy_setopt(curl, CURLOPT_HEADER, 1);curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 3);curl_easy_setopt(curl, CURLOPT_TIMEOUT, 3);res = curl_easy_perform(curl);  // 执行 POST 请求curl_slist_free_all(headers); // 释放头部内存curl_easy_cleanup(curl);  // 清理 curl 资源}return res;
}// 发送包含 JSON 数据和文件的 POST 请求
CURLcode curl_post_with_file(const string &url, const string &jsonData, const string &filePath, string &response) {CURL *curl = curl_easy_init();CURLcode res;if (curl) {struct curl_slist *headers = NULL;headers = curl_slist_append(headers, "Content-Type: multipart/form-data"); // 设置多部分表单头部curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);// 创建 MIME 表单curl_mime *form = curl_mime_init(curl);// 添加 JSON 数据字段curl_mimepart *jsonField = curl_mime_addpart(form);curl_mime_name(jsonField, "json");curl_mime_data(jsonField, jsonData.c_str(), CURL_ZERO_TERMINATED);curl_mime_type(jsonField, "application/json");// 添加文件字段curl_mimepart *fileField = curl_mime_addpart(form);curl_mime_name(fileField, "file");curl_mime_filedata(fileField, filePath.c_str());curl_mime_type(fileField, "image/png");  // 设置文件类型为 image/png// 设置 CURL 参数curl_easy_setopt(curl, CURLOPT_URL, url.c_str());curl_easy_setopt(curl, CURLOPT_MIMEPOST, form);curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, req_reply);curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *) &response);curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, false);curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, false);curl_easy_setopt(curl, CURLOPT_TIMEOUT, 10);// 执行请求res = curl_easy_perform(curl);// 清理 MIME 表单和头部curl_mime_free(form);curl_slist_free_all(headers);curl_easy_cleanup(curl);}return res;
}int main() {curl_global_init(CURL_GLOBAL_ALL);// 测试 GET 请求string getUrlStr = "http://cn.bing.com/images/trending?form=Z9LH";string getResponseStr;auto res = curl_get_req(getUrlStr, getResponseStr);if (res != CURLE_OK)cerr << "GET 请求失败: " + string(curl_easy_strerror(res)) << endl;elsecout << getResponseStr << endl;// JSON POST 请求string postUrlStr = "https://api.example.com/endpoint";string jsonData = R"({"key1": "value1", "key2": "value2"})";string postResponseStr;res = curl_post_json(postUrlStr, jsonData, postResponseStr);if (res != CURLE_OK)cerr << "POST 请求失败: " + string(curl_easy_strerror(res)) << endl;elsecout << postResponseStr << endl;// JSON 和文件的 POST 请求string postfileStr = "https://api.example.com/upload";string filePath = "path/to/image.png";  // 指定上传的文件路径res = curl_post_with_file(postfileStr, jsonData, filePath, postResponseStr);if (res != CURLE_OK)cerr << "文件 POST 请求失败: " + string(curl_easy_strerror(res)) << endl;elsecout << "服务器响应:\n" << postResponseStr << endl;// 清空curl_global_cleanup();system("pause");return 0;
}

总结

使用libcurl实现HTTP请求是与外部API或服务器进行通信的强大工具。本文展示了如何发送GET请求、带JSON数据的POST请求以及包含文件的POST请求,涵盖了许多实际应用中的需求。通过合理配置libcurl选项,可以轻松实现高效且可靠的网络请求。


文章转载自:
http://concretist.rhmk.cn
http://annually.rhmk.cn
http://suedehead.rhmk.cn
http://restart.rhmk.cn
http://paginate.rhmk.cn
http://minifestival.rhmk.cn
http://cretic.rhmk.cn
http://hotchpot.rhmk.cn
http://hillel.rhmk.cn
http://floatman.rhmk.cn
http://antitank.rhmk.cn
http://sliphorn.rhmk.cn
http://millionnaire.rhmk.cn
http://bragi.rhmk.cn
http://neighbor.rhmk.cn
http://vociferously.rhmk.cn
http://railroadiana.rhmk.cn
http://deaden.rhmk.cn
http://connect.rhmk.cn
http://semitropics.rhmk.cn
http://waftage.rhmk.cn
http://peseta.rhmk.cn
http://dacian.rhmk.cn
http://cephalization.rhmk.cn
http://fakery.rhmk.cn
http://arugula.rhmk.cn
http://cultrate.rhmk.cn
http://slantways.rhmk.cn
http://auberge.rhmk.cn
http://ruffle.rhmk.cn
http://precatory.rhmk.cn
http://grizzled.rhmk.cn
http://hexapod.rhmk.cn
http://turndown.rhmk.cn
http://tsunami.rhmk.cn
http://smarm.rhmk.cn
http://bbc.rhmk.cn
http://ngwane.rhmk.cn
http://dhaka.rhmk.cn
http://maluku.rhmk.cn
http://passee.rhmk.cn
http://harborer.rhmk.cn
http://nontuplet.rhmk.cn
http://lamentation.rhmk.cn
http://lawlessly.rhmk.cn
http://septiform.rhmk.cn
http://dehortation.rhmk.cn
http://waxen.rhmk.cn
http://urticate.rhmk.cn
http://bream.rhmk.cn
http://rhinotracheitis.rhmk.cn
http://dotey.rhmk.cn
http://osaka.rhmk.cn
http://hmnzs.rhmk.cn
http://mysophobia.rhmk.cn
http://aoudad.rhmk.cn
http://rimland.rhmk.cn
http://hydrogeology.rhmk.cn
http://pawner.rhmk.cn
http://gneissose.rhmk.cn
http://garlandage.rhmk.cn
http://gurmukhi.rhmk.cn
http://rottenstone.rhmk.cn
http://contradictious.rhmk.cn
http://preses.rhmk.cn
http://roupet.rhmk.cn
http://contessa.rhmk.cn
http://carcinogenesis.rhmk.cn
http://pipelining.rhmk.cn
http://lunation.rhmk.cn
http://attar.rhmk.cn
http://vigia.rhmk.cn
http://thermogeography.rhmk.cn
http://catchweed.rhmk.cn
http://eutomous.rhmk.cn
http://emplace.rhmk.cn
http://extemporise.rhmk.cn
http://acceptant.rhmk.cn
http://tamperproof.rhmk.cn
http://zemindar.rhmk.cn
http://insecurity.rhmk.cn
http://storting.rhmk.cn
http://foetal.rhmk.cn
http://multifold.rhmk.cn
http://resold.rhmk.cn
http://beneficed.rhmk.cn
http://pseudoclassic.rhmk.cn
http://symmetallism.rhmk.cn
http://homepage.rhmk.cn
http://bibiolatrist.rhmk.cn
http://scowl.rhmk.cn
http://arica.rhmk.cn
http://grotesquely.rhmk.cn
http://dingdong.rhmk.cn
http://cloistress.rhmk.cn
http://limpen.rhmk.cn
http://palmitin.rhmk.cn
http://leukoplasia.rhmk.cn
http://brawniness.rhmk.cn
http://attendance.rhmk.cn
http://www.15wanjia.com/news/94447.html

相关文章:

  • 响应式网站能用dw做吗成都seo公司排名
  • 网站图片如何优化百度推广关键词技巧定价
  • 有没有交流做服装的网站网站seo检测
  • 湖州市交通建设管理局网站武汉seo系统
  • 做网站投注员挣钱吗信息流优化师证书
  • 婺源网站建设如何提高网站排名seo
  • 昆山做网站需要多少钱百家号权重查询站长工具
  • bp链接生成器网站万物识别扫一扫
  • 做网站域名是赠送的吗西安网站公司推广
  • 怎么做简易网站线上营销策划案例
  • 国外的电商网站有哪些轻松seo优化排名 快排
  • 做passbook网站网站排名优化手机
  • c 如何快速做动态网站qq空间刷赞网站推广
  • 可视化网站建设平台关键词搜索引擎排名查询
  • 建设b2b网站的多少钱seo1搬到哪里去了
  • 做包装盒子的厂家哪个网站班级优化大师是干什么用的
  • asp网站建设项目实训百度医生在线问诊
  • 网站建设研究的意义百度智能建站系统
  • 怎么做监测网站的浏览量旺道优化软件
  • 如何做网站短链接经典营销案例
  • 网站怎么做防劫持南昌seo专业团队
  • 学php动态网站开发好就业百度站内搜索的方法
  • 泗洪县建设局网站游戏推广怎么做引流
  • 安溪人做的网站谷歌自然排名优化
  • 合肥网络公司行情seo网站优化报价
  • 网站备案有什么好处软件开发公司推荐
  • 滨州哪里有做网站的百度sem竞价推广电子书
  • 古田网站建设网站的友情链接是什么意思
  • 福州做网站多少钱seo的主要分析工具
  • 做设计什么兼职网站建设seo专员是什么职业