使用boost :: asio发送http GET请求,类似于cURL

时间:2015-02-25 19:52:30

标签: c++ curl boost boost-asio

我尝试使用某个域的REST API发送http GET请求。 基本上我要做的就是替换下面的卷曲请求:

    curl -k  -H "Content-Type: application/json" -X GET 
--data '{"username":"user@name.co", "password":"test"}' https:/domain.name/api/login/

使用boost::asio的一些c ++代码。 我不知道在这里找到所有的c ++代码,但有些检查点会很棒。

3 个答案:

答案 0 :(得分:4)

boost::asio不是应用程序级库。所以你可以用它打开一个连接,进行SSL握手等等。但是,您无法通过boost::asio构建HTTP请求,因为它仅用于发送/接收数据。

但是,您可以尝试使用this asio HTTP client example进行试验。这可能是一件好事。

答案 1 :(得分:4)

我发现自己也在使用boost来发送一些“自定义”HTTP GET请求 - 我在我的Ubuntu机器上本地运行服务器(16.04)。

在我的情况下,请求是我的服务器实现的一些专有API(与它保存在数据库中的单词相关),但您可以修改queryStr变量以保存您想要的任何查询字符串。

此外,在运行程序时更改argv[1]argv[2]以保留所需的值(IP地址,查询和端口,如果需要 - 默认为80)。

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

using boost::asio::ip::tcp;
using namespace std;

int main(int argc, char* argv[])
{
    cout << "main -start" << endl;
    try
    {
        boost::asio::io_service io_service;
        string ipAddress = argv[1]; //"localhost" for loop back or ip address otherwise, i.e.- www.boost.org;       
        string portNum = argv[2]; //"8000" for instance;
        string hostAddress;
        if (portNum.compare("80") != 0) // add the ":" only if the port number is not 80 (proprietary port number).
        {
             hostAddress = ipAddress + ":" + portNum;
        }
        else 
        { 
            hostAddress = ipAddress;
        }
        string wordToQuery = "aha";
        string queryStr = argv[3]; //"/api/v1/similar?word=" + wordToQuery;

        // Get a list of endpoints corresponding to the server name.
        tcp::resolver resolver(io_service);
        tcp::resolver::query query(ipAddress, portNum);
        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 " << queryStr << " HTTP/1.1\r\n";  // note that you can change it if you wish to HTTP/1.0
        request_stream << "Host: " << hostAddress << "\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");

        // 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");

        // 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;
        }

        // 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;
        }

        if (error != boost::asio::error::eof)
        {
              throw boost::system::system_error(error);
        }
    }
    catch (std::exception& e)
    {
        std::cout << "Exception: " << e.what() << "\n";
    }

    return 0;
}

我遵循的原始示例如下:Boost-simple-http-get-request-sync-client

希望它有用!

干杯,

盖。

答案 2 :(得分:1)

有一个Urdl库,由Boost.Asio的作者Christopher M. Kohlhoff创建:

  

Urdl是一个跨平台的C ++库,用于下载Web内容   一个URL。它为标准C ++ iostream提供了易于使用的扩展   和一个用于Boost.Asio的异步接口。

您的请求示例如下:

#include <urdl/http.hpp>

urdl::istream is;

// Set request options: method, content type, content
is.set_option(urdl::http::request_method("GET"));
is.set_option(urdl::http::request_content_type("application/json"));
is.set_option(urdl::http::request_content("{\"username\":\"user@name.co\", \"password\":\"test\"}"));

// open HTTP stream at URL
is.open("https:/domain.name/api/login/");
相关问题