sun博客

记录点滴!

使用c++做http通讯,走了不少坑。

坑一:由于使用的c++httplib,使用window的mingw 选择的win32版本,结果老是报错,最终原因发现要用posix版本,因于posix版本才支持多线程。

c++ httplib库链接:

https://github.com/yhirose/cpp-httplib

坑二:clion中文原因。clion的命令行窗口不显示中文的utf-8,总是乱码。配置改成以管理员运行后搞定。结果cmd的窗口也是乱码,因为cmd是gbk的编码。在main函数中添加以下代码搞定。

system("chcp 65001");

坑三:#define CPPHTTPLIB_OPENSSL_SUPPORT 此行代码要在httplib头文件之前。这样才能使用https的功能。但这些还不够,还需要链接以下代码:

#cmakelists配置
set(LIBRARY_OPENSSL_PATH "D:/Program Files/OpenSSL-Win64/bin/")
set(OPENSSL_INCLUDE_DIR "D:/Program Files/OpenSSL-Win64/include/")
add_executable(testApi test/testApi.cpp)
target_link_libraries(testApi PRIVATE ws2_32)
target_link_libraries(testApi PRIVATE wsock32)
target_link_libraries(testApi PRIVATE "${LIBRARY_OPENSSL_PATH}libcrypto-3-x64.dll")
target_link_libraries(testApi PRIVATE "${LIBRARY_OPENSSL_PATH}libssl-3-x64.dll")
target_include_directories(testApi PRIVATE ${OPENSSL_INCLUDE_DIR})
target_link_libraries(testApi PRIVATE "C:/Windows/System32/crypt32.dll")

整个https访问源码:

//
// Created by cxl on 2023/8/27.
//
#define CPPHTTPLIB_OPENSSL_SUPPORT
#include "../include/httplib.h"
#include <iostream>

using namespace std;

int main(){
    system("chcp 65001");
    string url="/redeem-code-mobile/redeemcode/redeemItems?redeemCode=";
    string cdk="4BUN226NK25V622W7";

    httplib::Client cli("https://m.ximalaya.com");
    httplib::Headers headers;
    headers.insert({"cookie","_xmLog=h5&9c2a952d-9f8d-4765-a6f2-8a2f05ee9ee9&2.4.18-alpha.0; 1&remember_me=y; 1&_token=467510970&EE24F570340C045D23D8BCB740AA6195D606E3DAEF564DC499D19F4EC07DACDA19A705167C1A189Ma427f67E24822D2_; login_type=code_mobile; impl=www.ximalaya.com.login; x_xmly_traffic=utm_source%253A%2526utm_medium%253A%2526utm_campaign%253A%2526utm_content%253A%2526utm_term%253A%2526utm_from%253A; Hm_lvt_4a7d8ec50cfd6af753c4f8aee3425070=1675074820,1675318738,1675475236,1675581801; Hm_lvt_e2abff7f9ca8c2fa2da3ef27e36bbc27=1675074757,1675328354,1675475231,1675674622; x_xmly_productId=74017724; Hm_lpvt_e2abff7f9ca8c2fa2da3ef27e36bbc27=1675761802; Hm_lpvt_4a7d8ec50cfd6af753c4f8aee3425070=1675930141; xm-page-viewid=hybrid-cdkeys-new"});

    auto res=cli.Get(url+cdk,headers);
   /* string content=httplib::detail::decode_url(res->body,true);
    cout<<"body value:"<<content<<'\n';*/
    cout<<"body2 value"<<res->body;
    string a;
    cin>>a;
    if(res->status==200){
      //  cout<<content;
    }
}

发表评论

邮箱地址不会被公开。 必填项已用*标注