问小白 wenxiaobai
资讯
历史
科技
环境与自然
成长
游戏
财经
文学与艺术
美食
健康
家居
文化
情感
汽车
三农
军事
旅行
运动
教育
生活
星座命理

httplib库对于https的使用

创作时间:
作者:
@小白创作中心

httplib库对于https的使用

引用
CSDN
1.
https://blog.csdn.net/soleil_moon/article/details/136874868

本文介绍了在C++中使用httplib库进行HTTPS请求的两种方法:使用httplib::Client和httplib::SSLClient。文章详细描述了如何处理证书认证问题,并提供了完整的代码示例。

使用httplib库进行HTTPS请求有两种方式:

第一种:使用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

© 2023 北京元石科技有限公司 ◎ 京公网安备 11010802042949号