HTTP + JSON 接口调用清单总结

cpp-httplib 库接口

cpp 复制代码
//客户端创建
httplib::Client::Client(const std::string& host)
void httplib::Client::set_connection_timeout(long sec, long usec)
void httplib::Client::set_read_timeout(long sec, long usec)
cpp 复制代码
//请求头
httplib::Headers::Headers()
cpp 复制代码
//POST 请求(核心)
httplib::Result httplib::Client::Post(
    const std::string& path,
    const httplib::Headers& headers,
    const std::string& body,
    const std::string& content_type
)
cpp 复制代码
//Result
// 1. 判断请求是否成功(Result 隐式转换)
httplib::Result::operator bool() const

// 2. 获取响应状态码 → **来自 Result 指向的 Response**
int httplib::Result::operator->()->status

// 3. 获取响应体字符串 → **来自 Result 指向的 Response**
std::string httplib::Result::operator->()->body

JsonCpp 库接口

cpp 复制代码
// 请求构建
Json::Value::Value()
Json::Value::Value(Json::arrayValue)
Json::Value& Json::Value::operator[](const char* key)
void Json::Value::append(const Json::Value& value)//数组 []

// 序列化
Json::StringWriterBuilder::StringWriterBuilder()
Json::Value& Json::StringWriterBuilder::operator[](const char* key)
std::string Json::writeString(Json::StreamWriterBuilder&, const Json::Value&)
// 反序列
Json::CharReaderBuilder::CharReaderBuilder()
bool Json::parseFromStream(Json::CharReaderBuilder&, std::istream&, Json::Value*, std::string*)
// 响应判断 、取值
bool Json::Value::isMember(const char*) const
bool Json::Value::isArray() const
bool Json::Value::empty() const
bool Json::Value::isObject() const
bool Json::Value::isString() const
std::string Json::Value::asString() const

📌 示例场景3

cpp 复制代码
POST https://example.com/api/chat

请求:

XML 复制代码
{
  "model": "test-model",
  "messages": [
    {
      "role": "user",
      "content": "你好"
    }
  ]
}

响应:

XML 复制代码
{
  "id": "chat123",
  "choices": [
    {
      "message": {
        "role": "assistant",
        "content": "你好!有什么可以帮你?"
      }
    }
  ]
}

要求完成接口:

cpp 复制代码
std::string chat(const std::string& userInput);// userInput就是用户发给模型的一句话

参考代码:

cpp 复制代码
std::string chat(const std::string& userInput)
{
    //一、发送请求
        //op1:创建客户端
      httplib::Client client("https://example.com");
      client.set_connection_timeout(10,0);
      client.set_read_timeout(60,0);
        //op2:构建请求
      httplib::Headers headers = {
      {"Content-Type","application/json"}
      };
      Json::Value requestBody;
      requestBody["model"] = "test-model";
      Json::Value messagesArray(Json::arrayValue);
      Json::Value message;
      message["role"]= "user";
      message["content"] = userInput;
      messagesArray.append(message);
      requestBody["messages"] = messagesArray;
      
      Json::StringWriterBuilder swb;
      swb["indentation"] = "";
      auto body = Json::writeString(swb,requestBody);
        //op3:发送请求
      auto result = client.Post("/api/chat",headers,body,"application/json");
      if(!result)
      {
          bear::ERROR("chat send POST FAILED or dont recv response ERROR");
          return "";
      }
    //二、接收响应
        //op1:判断响应码
       bear::INFO("chat send POST success ,response status:{}",result->status);
       bear::INFO("chat send POST success ,response body:{}",result->body);
       if(result->status != 200)
       {
           return "";
       }
        //op2:反序列化
        Json::Value responseBody;
        std::string errResponse;
        Json::CharReaderBuilder crb;
        std::istringstream datSrc(result->body);
        auto ret = Json::parseFromStream(crb,datSrc,&responseBody,&errResponse);
        if(ret == false)
        {
            bear::ERROR("chat recv response but parseFromStream FAILED:{}",errResponse.c_str());
            return "";
        }
        //op3:解析响应
        if(responseBody.isMember("choices") && responseBody["choices"].isArray() && !responseBody["choices"].empty())
        {
            auto choices = responseBody["choices"][0];
            if(choices.isMember("message") && choices["message"].isObject())
            {
                if(choices["message"].isMember("content")&& choices["message"]["content"].isString())
                {
                    std::string replyString = choices["message"]["content"].asString();
                    return replyString; 
                }
            }
        }
        bear::ERROR("chat recv response but content not found");
        return "";
}
相关推荐
loopfde成序2 小时前
Web-RAG 检索可见度评估体系与站点 JSON-LD 及 llms.txt 自动化核验实践
前端·自动化·json
郝学胜-神的一滴20 小时前
Effective STL 条款12:对容器线程安全性的现实期望
c语言·开发语言·c++·qt·网络协议·rpc·numpy
FakeOccupational1 天前
fpga系列 HDL : 选择RAM IP(Two Port IP核) 乒乓缓冲(Ping-Pong Buffer)工作流程
网络协议·tcp/ip·fpga开发
爱和冰阔落1 天前
【Linux网络】GET 和 POST 真的只是参数位置不同吗?从 HTTP 请求方法、抓包分析到长连接与路由实战
linux·c++·http·网络编程·get与post
可涵不会debug1 天前
ChatServer 模块学习笔记:HTTP 接入层、多线程与流式响应
笔记·学习·http
laozhang7002 天前
自己动手写一个 WebSocket 调试工具:告别广告与限制
网络·websocket·网络协议
AndreaYYmm2 天前
AF_PACKET 原始套接字抓包实战:手写一个 mini-tcpdump
c语言·网络协议
捷焱GEO2 天前
用本地 HTTP 用例验证旧活动页的退役状态
网络·网络协议·http·seo
AllData公司负责人3 天前
实战二:AllData大模型与AI数据底座-数据传输平台-DBSyncer,搭建 Http 接口同步至 Doris,API 业务数据自动拉取入数仓
大数据·数据库·数据仓库·人工智能·算法·http·doris
云上工程笔记3 天前
企业大模型调用数据安全与合规怎么保障:2026 年等保、数据留存、密钥与 IP 白名单清单
数据库·网络协议·tcp/ip