You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用httplib cpp发起HTTP请求时遇到308状态码的问题排查

问题:用httplib cpp请求API返回308状态码无法获取响应体

我尝试用httplib cpp向http://api.publicapis.org/entries发起HTTP请求,代码如下:

httplib::Client cli("http://api.publicapis.org");

if (auto res = cli.Get("/entries")) {
    if (res->status == 200) {
        std::cout << res->body << std::endl;
    }
} else {
    auto err = res.error();
    std::cout << "HTTP error: " << httplib::to_string(err) << std::endl;
}

但收到状态码308,没法打印响应体,请问问题出在哪?


解决方案

308是永久重定向状态码,本质原因是这个API要求使用HTTPS协议访问,而你代码里用的是HTTP协议。

两种解决办法:

  • 直接改用HTTPS初始化Client(推荐)
    把Client的地址改成https://api.publicapis.org,代码修改后如下:
httplib::Client cli("https://api.publicapis.org");

if (auto res = cli.Get("/entries")) {
    if (res->status == 200) {
        std::cout << res->body << std::endl;
    } else {
        std::cout << "Response status: " << res->status << std::endl;
    }
} else {
    auto err = res.error();
    std::cout << "HTTP error: " << httplib::to_string(err) << std::endl;
}
  • 开启自动跟随重定向
    如果不想改地址,可以让httplib自动处理重定向,添加一行配置:
httplib::Client cli("http://api.publicapis.org");
cli.set_follow_redirects(true); // 开启自动跟随重定向

if (auto res = cli.Get("/entries")) {
    if (res->status == 200) {
        std::cout << res->body << std::endl;
    }
} else {
    auto err = res.error();
    std::cout << "HTTP error: " << httplib::to_string(err) << std::endl;
}

第一种方法更直接,因为API已经永久重定向到HTTPS,直接用HTTPS可以减少一次重定向请求的开销。

内容的提问来源于stack exchange,提问作者Riccardo Perego

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 19:24:27