代码之家  ›  专栏  ›  技术社区  ›  LuisGP

如何获取curlpp响应标头

  •  0
  • LuisGP  · 技术社区  · 6 年前

    我使用JSON负载调用REST WS来订阅特定事件。服务器应答,HTTP代码为201,字段名为 地方 在HTTP标头中,使用订阅的ID。

    例如,在curl(-v)中,我们得到:

    [...]
    < HTTP/1.1 201 Created
    < Connection: Keep-Alive
    < Content-Length: 0
    < Location: /v2/subscriptions/5ab386ad4bf6feec37ffe44d
    [...]
    

    在使用curlpp的C++中,我们希望通过查看响应头来检索该id。现在我们只有身体反应(在本例中为空)。

    std::ostringstream response;
    subRequest.setOpt(new curlpp::options::WriteStream(&response));
    
    // Send request and get a result.
    subRequest.perform();
    
    cout << response.str() << endl;
    

    我们如何获得 地方 C++中使用curlpp的标题字段(其在示例中的内容是“/v2/subscriptions/5ab386ad4bf6feec37ffe44d”)?

    2 回复  |  直到 6 年前
        1
  •  2
  •   Eelke    6 年前

    有几个值可以使用 curlpp::infos::*::get 功能。例如,HTTP响应代码:

    curlpp::infos::ResponseCode::get(subRequest) 
    

    请参见 Infos.hpp 完整列表的标题。当您需要一个无法通过这些信息之一获得的值时,您还可以选择在回调中从正文中单独接收标题。

    subRequest.setOpt(new curlpp::options::HeaderFunction(
        [] (char* buffer, size_t size, size_t items) -> size_t {
            std::string s(buffer, size * items); // buffer is not null terminated
            std::cout << s;
            return size * items;
        }));
    
        2
  •  2
  •   LuisGP    6 年前

    好的,我找到了。

    简单地加上

    subRequest.setOpt(new curlpp::options::Header(1));
    

    执行此技巧并在响应中存储标题。