c++ - 如何使用 Boost::Asio 访问 Web 服务?

标签 c++ ios boost webservices-client

我想知道是否有可能使用 boost asio 库访问网络服务。

我尝试了以下从 boost asio 文档中获得的代码(在 IOS、C++11 中)。 但它抛出以下内容。

try
{
    boost::asio::io_service io_service;
    std::string address = "http://www.thomas-bayer.com/axis2/services/BLZService/";

    // Get a list of endpoints corresponding to the server name.
    tcp::resolver resolver(io_service);
    tcp::resolver::query query(address,boost::asio::ip::resolver_query_base::numeric_service);


    tcp::resolver::iterator endpoint_iterator = resolver.resolve(query);

    endpoint_iterator->host_name() = "www.thomas-bayer.com/axis2/services/BLZService/";

    std::cout<<"Print Query --"<<std::endl;

    // 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 << "POST: HTTP/1.0\r\n";
    request_stream << "Host: " << address << "\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;
    }
    if (status_code != 200)
    {
        std::cout << "Response returned with status code " << status_code << "\n";
        return;
    }

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

Exception: connect: Can't assign requested address

或者

Exception: resolve: Host not found (authoritative)

代码有什么问题吗?或者我做的完全错误?

谢谢

最佳答案

名称解析失败,因为您混淆了请求、URL、协议(protocol)、主机名和 IP 地址。

FQDN 上执行请求。除非您知道,否则您需要提供服务。本例中的服务遵循协议(protocol) 1,`http://通常在端口 80 上提供服务:

std::string const address = "www.thomas-bayer.com";
tcp::resolver::query query(address, "80", boost::asio::ip::resolver_query_base::numeric_service);

请注意,在大多数系统上您可以等效地使用:

std::string const address = "www.thomas-bayer.com";
tcp::resolver::query query(address, "http");

看看 http://www.thomas-bayer.com 部分去了哪里?

现在 /axis2/services/BLZService/ 是查询路径,就像您在 GET 请求中写入的那样:

request_stream << "GET /axis2/services/BLZService/ HTTP/1.1\r\n";

注释:

  1. POST 不是 header (因此没有冒号!),而是 HTTP“动词”(GET、POST、DELETE、PUT...)
  2. “Host” header 主机名:

     request_stream << "Host: " << address << "\r\n";
    

    正确iff 地址确实是主机的逻辑名称

  3. 像这样设置主机名:

     endpoint_iterator->host_name() = "www.thomas-bayer.com/axis2/services/BLZService/";
    

    是我以前从未见过的东西,我不确定它应该实现什么。也许这只是错误的?

¹ 按照惯例,它可能是其他

修复

#include <boost/asio.hpp>
#include <iostream>
using boost::asio::ip::tcp;

void test() try {
    boost::asio::io_service io_service;
    std::string const address = "www.thomas-bayer.com";

    // Get a list of endpoints corresponding to the server name.
    tcp::resolver resolver(io_service);
    tcp::resolver::query query(address, "80", boost::asio::ip::resolver_query_base::numeric_service);

    tcp::resolver::iterator endpoint_iterator = resolver.resolve(query);

    std::cout << "Print Query --" << std::endl;

    // 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 /axis2/services/BLZService HTTP/1.0\r\n";
    request_stream << "Host: " << address << "\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, status_message;
    unsigned int status_code;
    std::getline(response_stream >> http_version >> status_code, status_message);

    if (!response_stream || http_version.substr(0, 5) != "HTTP/") {
        std::cout << "Invalid response\n";
        return;
    }
    if (status_code != 200) {
        std::cout << "Response returned with status code " << status_code << "\n";
        return;
    }

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

int main() { test(); }

关于c++ - 如何使用 Boost::Asio 访问 Web 服务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44386919/

相关文章:

ios - 为什么我的 UIPageViewController 中的页面没有变化?

C++ boost date_input_facet 似乎使用传递给 facet 构造函数的不正确格式意外地解析日期

c++ - 使用 boost::asio 时的引用问题(我猜)

c++ - 我是否也仅在函数头或声明中指定异常类型? (C++)

c++ - 当.h和.cpp文件中的定义和声明分开时,getter和setter可以内联吗?

c++ - 在 C++ 中使用按引用和按值传递的变量的时机

c++ - 无法安装boost ubuntu 13.10

c++ - Windows 服务生命周期和职责

ios - [CFString保持]:消息发送到释放

ios - 信号量在我的案例中没有按预期工作