在C ++中解析HTTP标头 [英] Parse HTTP headers in C++

查看:78
本文介绍了在C ++中解析HTTP标头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用curl与服务器进行通信.

I am using curl to communicate with a server.

当我请求数据时,我收到HTTP标头,后跟jpeg数据,并用边界分隔,如下所示:

When I make a request for data I receive the HTTP headers followed by jpeg data separated by a boundary like so:

我需要解析

  1. 边界字符串
  2. 内容长度.

我已将输入的数据复制到一个char数组中,如下所示:

I have copied the incoming data to a a char array like so:

static size_t OnReceiveData ( void * pvData, size_t tSize, size_t tCount, void * pvUser )
{
    printf("%*.*s", tSize * tCount, tSize * tCount, pvData);

    char* _data;
    if(pvData != nullptr && 0 != tCount)
    {
        _data = new char[tCount];
       memcpy(_data, pvData, tCount);
    }

    return ( tCount );
}

我怎样才能最好地用C ++做到这一点?我实际上如何检查并解析_data数组以获得所需的信息?例如,我可以使用任何增强库吗?

How can I best do this in C++?? How do I actually inspect and parse the _data array for the information that I want?? Are the any boost libraries that I can use for example??

推荐答案

您可以动态解析标头,也可以将标头放入地图中并在以后进行后处理.使用std :: string .查看 Boost字符串算法库,其中包含许多算法,例如修剪

You could parse the headers on the fly or put them into a map and post-process later. Use find, substr methods from the std::string. Look at Boost String Algorithms Library, it contains lots of algorithms, e.g. trim

例如将标头放入 std :: map 并将其打印(粗略显示):

e.g. to place headers into the std::map and print them (rough cuts):

#include <stdlib.h>
#include <iostream>
#include <sstream>
#include <string>
#include <map>
#include <boost/algorithm/string.hpp>

int main(int argc, char* argv[]) {
  const char* s = "HTTP/1.1 200 OK\r\n"
    "Content-Type: image/jpeg; charset=utf-8\r\n"
    "Content-Length: 19912\r\n\r\n";

  std::map<std::string, std::string> m;

  std::istringstream resp(s);
  std::string header;
  std::string::size_type index;
  while (std::getline(resp, header) && header != "\r") {
    index = header.find(':', 0);
    if(index != std::string::npos) {
      m.insert(std::make_pair(
        boost::algorithm::trim_copy(header.substr(0, index)), 
        boost::algorithm::trim_copy(header.substr(index + 1))
      ));
    }
  }

  for(auto& kv: m) {
    std::cout << "KEY: `" << kv.first << "`, VALUE: `" << kv.second << '`' << std::endl;
  }

  return EXIT_SUCCESS;
}

您将获得输出:

KEY: `Content-Length`, VALUE: `19912`
KEY: `Content-Type`, VALUE: `image/jpeg; charset=utf-8`

有了标题,您可以提取所需的标题以进行后期处理.

Having the headers, you could extract the required ones for post-processing.

这篇关于在C ++中解析HTTP标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆