使用了 httplib
库,链接,使用该库只需要包含头文件即可,另外在Windows环境下,使用mingw构建项目,需要在编译时链接网络编程库,task.json如下:
{"version": "2.0.0","tasks": [{"type": "cppbuild","label": "C/C++: g++.exe 生成活动文件","command": "D:\\xxx\\mingw64\\mingw64\\bin\\g++.exe","args": ["-fdiagnostics-color=always","--std=c++17",//确保std::filesystem可以使用"-g","${workspaceFolder}\\src\\*.cpp","-I","${workspaceFolder}\\include","-o","${fileDirname}\\${fileBasenameNoExtension}.exe","-lstdc++fs",//确保std::filesystem可以使用"-lwsock32",//网络编程库"-lws2_32"//这两个都是],"options": {"cwd": "${fileDirname}"},"problemMatcher": ["$gcc"],"group": {"kind": "build","isDefault": true},"detail": "编译器: \"D:\\xxx\\mingw64\\mingw64\\bin\\g++.exe\""}]
}
网上看到了很多好用的http调试工具,比如一款开源免费的 postwoman ,但是我想测试自己的程序中post的数据目标有没有收到,没有在postwoman中找到监听功能,后来发现了一个有echo功能的测试接口 http://httpbin.org/post
,可以原样返回向他发送的请求头以及参数等,下面是一个简单的测试样例:
#include<iostream>
#include <httplib.h>
#include "nlohmann/json.hpp"//json库,也即包含头文件就可用using namespace std;int main() {httplib::Client client("httpbin.org", 80);httplib::Params params;params.emplace("name", "john");params.emplace("note", "coder");// 发起 HTTP POST 请求到指定路径 "/post"auto res = client.Post("/post", params);// 检查请求是否成功if (res && res->status == 200) {// 打印响应体std::cout << res->body << std::endl;// 可以进一步处理响应的内容,例如解析为 JSON} else {// 处理请求失败的情况auto err = res.error();std::cerr << "错误:" << err << std::endl;}return 0;
}
输出:
{"args": {},"data": "","files": {},"form": {"name": "john","note": "coder"},"headers": {"Accept": "*/*","Content-Length": "20","Content-Type": "application/x-www-form-urlencoded","Host": "httpbin.org","User-Agent": "cpp-httplib/0.14.3","X-Amzn-Trace-Id": "Root=1-65dfdb62-62b001d33ee6f2193119e45c"},"json": null,"origin": "211.64.159.21","url": "http://httpbin.org/post"
}
几个很好的博主分享:
HTTP中POST提交数据的四种方式详解
nlohmann入门使用总结
httplib库的使用(支持http/https)(一)
原来C++调用HTTP API接口也能这么优雅