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



我正在尝试使用某个域的REST API发送一个http GET请求。基本上,我想做的是替换以下curl请求:

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

用CCD_ 1编写了一些c++代码。我不想在这里找到所有的c++代码,但有些检查点会很棒。

我发现自己也在使用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.1rn";  // note that you can change it if you wish to HTTP/1.0
        request_stream << "Host: " << hostAddress << "rn";
        request_stream << "Accept: */*rn";
        request_stream << "Connection: closernrn";
        // 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, "rn");
        // 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 responsen";
            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, "rnrn");
        // 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简单http获取请求同步客户端

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

但是,您可以尝试试用这个asioHTTP客户端示例。也许这是一件好事。

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

Urdl是一个跨平台的C++库,用于使用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/");

最新更新