本文记载自己使用httplib库进行https请求的心得
使用httplib库进行https请求有两种方式:
我们使用post举例
第一种:使用httplib::Client
这种方法要在url中声明为https
string surl = "https://ip_address:port" //ip_address 表示实际ip,port表示实际端口,或者填域名
https请求牵扯到一个证书认证问题,我们可以使用证书,也可以不使用证书,
依赖两个函数
//用于启用或禁用证书,false表示禁用
Client::enable_server_certificate_verification(bool enabled)
//设置认证证书路径
Client::set_ca_cert_path(const std::string &ca_cert_file_path,
const std::string &ca_cert_dir_path)
完整代码
#include "httplib.h" //这里填实际路径,我是在makefile中已经指定路径了
int main()
{
//ip_address 表示实际ip,port表示实际端口,或者填域名
string surl = "https://127.0.0.1:8888";
httplib::Client cli(surl);
// enable_server_certificate_verification用于启用或禁用证书,false表示禁用,
// 如果要使用证书验证的话,值传true,同时调用cli.set_ca_cert_path(),参数传客户端证书路径
cli.enable_server_certificate_verification(false);
httplib::Headers headers = {
{"content-type", "application/json"}};
string request = R"({"key1": "value1", "key2": "value2"})"; // 实际请求数据,一般是json数据
auto res = cli.Post("/api/heartbeat", headers, request, "application/json");
if (res == nullptr)
{
HGINF("res is null , error = %s", to_string(res.error()).c_str());
return;
}
std::string response_body = res->body;
}
备注:header的设置和post请求有多种方式,可以根据实际需要灵活使用
第二种使用httplib::SSLClient
#include "httplib.h"
int main()
{
httplib::SSLClient cli("127.0.0.1", 8888);
cli.set_default_headers({
{"Content-Type", "application/json"}
});
cli.enable_server_certificate_verification(false);
string request = R"({"key1": "value1", "key2": "value2"})"; // 实际请求数据,一般是json数据
auto res = cli.Post("/api/heartbeat", request , "application/json");
if (res == nullptr)
{
printf("res is null , error = %s\n",to_string(res.error()).c_str());
return 0;
}
printf("status: %d \n",res->status );
printf("body: %s\n",res->body.c_str());
}
备注:
1.使用https时,makefile文件中要增加 libssl 和 libcrypt两个库文件的引入
2.要定义头文件 #define CPPHTTPLIB_OPENSSL_SUPPORT,这个宏定义用来开启openssl,
程序单线程时,可以在调用的cpp中定义,如这样,定义必须在引入头文件前
#define CPPHTTPLIB_OPENSSL_SUPPORT
#include "httplib.h"
如果多线程的话,最好在httplib.h这个头文件中去定义,
否则运行时会报错
virtual bool httplib::SSLClient::process_socket(const httplib::ClientImpl::Socket&, std::function<bool(httplib::Stream&)>): Assertion `socket.ssl' failed