boost执行http的GET请求

boost执行http的GET请求。

//
//#include <libs/asio/example/cpp03/http/client/sync_client.cpp>
//此代码以"boost_1_58_0_7z/libs/asio/example/cpp03/http/client/sync_client.cpp"为蓝本,略作修改.
//

//
// sync_client.cpp
// ~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2015 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//

#include <iostream>
#include <istream>
#include <ostream>
#include <string>
#include <boost/asio.hpp>

using boost::asio::ip::tcp;

inline int boost_http_sync_client(const std::string& server, const std::string& port, const std::string& path,
    std::string& out_response_status_line, std::string& out_response_header, std::string& out_response_data)
{
  try
  {
    boost::asio::io_service io_service;

    // Get a list of endpoints corresponding to the server name.
    tcp::resolver resolver(io_service);
    tcp::resolver::query query(server, port/*"http"*/);
    tcp::resolver::iterator endpoint_iterator = resolver.resolve(query);

    // Try each endpoint until we successfully establish a connection.
    tcp::socket socket(io_service);
    boost::asio::connect(socket, endpoint_iterator);

    // Form the request. We specify the "Connection: close" header so that the
    // server will close the socket after transmitting the response. This will
    // allow us to treat all data up until the EOF as the content.
    boost::asio::streambuf request;
    std::ostream request_stream(&request);
    request_stream << "GET " << path/*argv[2]*/ << " HTTP/1.0\r\n";
    request_stream << "Host: " << server/*argv[1]*/ << "\r\n";
    request_stream << "Accept: */*\r\n";
    request_stream << "Connection: close\r\n\r\n";

    // Send the request.
    boost::asio::write(socket, request);

    // Read the response status line. The response streambuf will automatically
    // grow to accommodate the entire line. The growth may be limited by passing
    // a maximum size to the streambuf constructor.
    boost::asio::streambuf response;
    boost::asio::read_until(socket, response, "\r\n");

    if (true)
    {
        boost::asio::streambuf::const_buffers_type cbt = response.data();
        std::string temp_data(boost::asio::buffers_begin(cbt), boost::asio::buffers_end(cbt));
        std::size_t idx = temp_data.find('\n');
        idx == std::string::npos ? temp_data.size() : idx;
        out_response_status_line = temp_data.substr(0, idx + 1);
    }

    // Check that response is OK.
    std::istream response_stream(&response);
    std::string http_version;
    response_stream >> http_version;
    unsigned int status_code;
    response_stream >> status_code;
    std::string status_message;
    std::getline(response_stream, status_message);
    if (!response_stream || http_version.substr(0, 5) != "HTTP/")
    {
      std::cout << "Invalid response\n";
      return 1;
    }
    if (status_code != 200)
    {
      std::cout << "Response returned with status code " << status_code << "\n";
      return 1;
    }

    // Read the response headers, which are terminated by a blank line.
    boost::asio::read_until(socket, response, "\r\n\r\n");
    if (true)
    {
        boost::asio::streambuf::const_buffers_type cbt = response.data();
        std::string temp_data(boost::asio::buffers_begin(cbt), boost::asio::buffers_end(cbt));
        std::size_t idx = temp_data.find("\r\n\r\n");
        idx == std::string::npos ? temp_data.length() : idx;
        out_response_header = temp_data.substr(0, idx + 2);
    }

    // Process the response headers.
    std::string header;
    while (std::getline(response_stream, header) && header != "\r")
        ;//std::cout << header << "\n";
    //std::cout << "\n";

    // Write whatever content we already have to output.
    //if (response.size() > 0)
    //    std::cout << &response;
    if (true)
    {
        boost::asio::streambuf::const_buffers_type cbt = response.data();
        out_response_data = std::string(boost::asio::buffers_begin(cbt), boost::asio::buffers_end(cbt));
    }

    // Read until EOF, writing data to output as we go.
    boost::system::error_code error;
    while (boost::asio::read(socket, response,
          boost::asio::transfer_at_least(1), error))
        //std::cout << &response;
    {
        boost::asio::streambuf::const_buffers_type cbt = response.data();
        out_response_data += std::string(boost::asio::buffers_begin(cbt), boost::asio::buffers_end(cbt));
    }
    if (error != boost::asio::error::eof)
      throw boost::system::system_error(error);
  }
  catch (std::exception& e)
  {
    std::cout << "Exception: " << e.what() << "\n";
    return -1;
  }

  return 0;
}
//
//可以解析下列三种类型的URL:
//http://yunhq.sse.com.cn:32041/v1/sh1/snap/204001?callback=jQuery_test&select=name%2Clast%2Cchg_rate%2Cchange%2Camount%2Cvolume%2Copen%2Cprev_close%2Cask%2Cbid%2Chigh%2Clow%2Ctradephase
//http://hq.sinajs.cn/list=sh204001
//https://www.baidu.com
//
inline int parse_url(const std::string& url, std::string& out_server, std::string& out_port, std::string& out_path)
{
    const std::string http___ = "http://";
    const std::string https___ = "https://";
    std::string temp_data = url;

    if (temp_data.find(http___) == 0)
        temp_data = temp_data.substr(http___.length());
    else if (temp_data.find(https___) == 0)
        temp_data = temp_data.substr(https___.length());
    else
        return -1;

    std::size_t idx = temp_data.find('/');
    if (std::string::npos == idx)
    {
        out_path = "/";
        idx = temp_data.size();
    }
    else
    {
        out_path = temp_data.substr(idx);
    }

    out_server = temp_data.substr(0, idx);
    idx = out_server.find(':');
    if (std::string::npos == idx)
    {
        out_port = "http";
        out_port = "80";
    }
    else
    {
        out_port = out_server.substr(idx + 1);
        out_server = out_server.substr(0, idx);
    }

    return 0;
}
//
inline int get_url_response(const std::string& url, std::string& out_response_data)
{
    int rv = 0;
    do
    {
        std::string server;
        std::string port;
        std::string path;
        rv = parse_url(url, server, port, path);
        if (rv)  break;
        std::string out_response_status_line;
        std::string out_response_header;
        rv = boost_http_sync_client(server, port, path, out_response_status_line, out_response_header, out_response_data);
        if (rv)  break;
    } while (false);
    return rv;
}
//
int parse_hq_sinajs_cn_and_get_last_price(const std::string& market_data, double& last_price)
{
    std::string temp_data = market_data;
    std::size_t idx;

    idx = temp_data.find('"');
    if (std::string::npos == idx)
        return -1;
    temp_data = temp_data.substr(idx + 1);

    idx = temp_data.find('"');
    if (std::string::npos == idx)
        return -1;
    temp_data = temp_data.substr(0, idx);

    std::vector<std::string> fields;
    std::size_t beg_idx, end_idx;
    for (beg_idx = end_idx = 0; (end_idx = temp_data.find(',', beg_idx)) != std::string::npos; beg_idx = end_idx + 1)
        fields.push_back(temp_data.substr(beg_idx, end_idx - beg_idx));
    fields.push_back(temp_data.substr(beg_idx));

    if (fields.size() != 33)
        return -1;

    last_price = atof(fields[3].c_str());

    return 0;
}
//
int main()
{
    int rv = 0;
    std::string url = "http://hq.sinajs.cn/list=sh204001";
    std::string response_data;
    rv = get_url_response(url, response_data);
    if (rv)  return -1;
    std::cout << response_data << std::endl;

    double last_price = 0;
    rv = parse_hq_sinajs_cn_and_get_last_price(response_data, last_price);
    if (rv)  return -1;
    std::cout << last_price << std::endl;

    return 0;
}

完。

### 回答1: Boost是一个在C++标准库之上提供可移植、跨平台的增强功能的开源库。Boost.httpBoost库中的一个模块,它提供了HTTP协议的支持,使得C++程序能够更方便地实现HTTP通信。 Boost.http库提供了一组类和函数,用于处理HTTP请求和响应。通过这些类和函数,我们可以方便地发送HTTP请求、接收HTTP响应,并处理请求和响应的各种属性,例如请求头、响应头、请求参数等。 在使用Boost.http库实现HTTP功能时,我们首先需要创建一个HTTP客户端或服务器对象。客户端对象用于发送HTTP请求,而服务器对象用于接收和处理HTTP请求。 对于HTTP客户端,我们可以使用boost::beast::http::request类来构造HTTP请求并发送,例如构造一个GET请求发送到指定的URL地址。在发送请求后,我们可以通过读取boost::beast::http::response类来获取HTTP响应。 对于HTTP服务器,我们可以使用boost::beast::http::request_parser类来解析接收到的HTTP请求,然后根据请求的内容进行相应的处理。处理完毕后,可以使用boost::beast::http::response_creator类来构造HTTP响应并发送回客户端。 Boost.http库还提供了其他一些有用的功能,例如重定向、处理cookie、处理SSL等。 通过使用Boost.http库,我们可以更方便地实现基于HTTP协议的网络通信功能。而且,由于Boost库的可移植性和跨平台性,我们的代码可以在不同的操作系统和编译器上运行,极大地增强了程序的可移植性和可扩展性。 ### 回答2: C++是一种强大的编程语言,而Boost库则是C++语言中的一个重要工具。Boost库提供了大量的功能和算法,可以帮助开发者更高效地进行C++编程。其中,Boost库中的Boost.Asio模块提供了对HTTP/HTTPS和网络编程的支持。 在Boost库中使用Boost.Asio模块实现HTTP/Web功能,需要以下步骤: 1. 引入Boost库:首先,我们需要在自己的项目中引入Boost库。可以通过下载Boost库源代码并进行编译,或者直接使用已经编译好的二进制包。 2. 包含Asio头文件:在我们的代码中,需要包含Asio头文件,以便使用其中提供的HTTP/HTTPS和网络编程相关类和函数。 3. 创建HTTP请求和响应:使用Asio提供的类和函数,我们可以创建HTTP请求和响应对象,并设置相应的请求方法、URL、头部信息等。 4. 发送HTTP请求:通过Asio提供的socket对象,我们可以将HTTP请求发送到服务器,并等待服务器的响应。 5. 接收HTTP响应:当服务器返回响应时,我们可以使用Asio提供的相应函数,将响应内容保存到相应的数据结构中,以便我们进一步处理。 6. 处理响应:根据服务器返回的HTTP响应内容,我们可以进行相应的处理,如解析HTML、处理JSON数据等。 7. 关闭连接:当所有的请求和响应处理完成后,我们可以关闭与服务器的连接。 使用Boost库的Asio模块,我们可以很方便地实现HTTP/Web功能,包括发送HTTP请求、接收和处理服务器的响应等。通过充分利用Boost库的强大功能,我们可以编写高效、稳定的C++代码,实现各种应用程序中的网络功能。 ### 回答3: C++是一种高级编程语言,常用于开发高性能和跨平台的应用程序。Boost库是一个开源的C++库,提供了很多通用的功能组件和工具,用于增强C++程序的功能。而HTTP是一种基于客户端-服务器模型的协议,用于在Web上进行数据通信。 在C++中,我们可以使用Boost库中的ASIO模块来实现基于HTTP的Web应用程序。ASIO(Asynchronous Input/Output)是一种基于事件驱动的异步I/O库,能够实现高效的网络通信。 为了实现HTTP的功能,我们可以使用Boost库中的HTTP模块。这个模块提供了HTTP的解析器和生成器,可以用于解析HTTP请求和构建HTTP响应。 使用Boost库实现HTTP Web应用程序的一般步骤如下: 1. 导入Boost库:在C++项目中,首先需要将Boost库导入到项目中。可以从官方网站下载编译好的Boost库,然后将其链接到项目中。 2. 创建HTTP服务器:使用Boost库的ASIO模块创建一个HTTP服务器对象。这个服务器将监听指定的端口,接收和处理客户端的HTTP请求。 3. 处理HTTP请求:当服务器接收到客户端的HTTP请求时,使用Boost库中的HTTP模块解析该请求,并提取请求的内容以及其他相关信息。根据请求的内容和参数执行相应的操作。 4. 响应HTTP请求:根据处理结果,使用Boost库中的HTTP模块生成HTTP响应,并将其发送给客户端。HTTP响应包括状态码、响应头和响应体等内容。 5. 清理资源:在服务器不再需要监听请求时,需要及时关闭服务器对象,并清理相关的资源。 总结起来,使用Boost库的ASIO和HTTP模块,可以方便地实现基于HTTP的Web应用程序。通过解析HTTP请求和生成HTTP响应,我们可以实现各种功能,如网页服务、文件传输、数据交互等。 Boost库提供了丰富的功能和工具,可以大大提高C++程序的开发效率和性能。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值