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

2023-11-22

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

    curl -k  -H "Content-Type: application/json" -X GET 
--data '{"username":"u[email protected]", "password":"test"}' https:/domain.name/api/login/

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


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

就我而言,请求是我的服务器实现的某些专有 API(与其数据库中保存的单词相关),但您可以修改queryStr变量来保存您想要的任何查询字符串。

另外,更改argv[1] and 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

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用boost::asio发送http GET请求,类似于cURL 的相关文章

  • Qt 和 Sqlite 示例

    我正在寻找一些使用 Qt 的示例代码 它是带有 Sqlite 驱动程序的 SQL 模块 我需要示例的主要原因是我之前有 Qt 数据库接口的经验 并且 Sqlite 在字段类型方面有一些奇怪的行为 类型是按字段存储的 而不是按列存储的 The
  • 使用遗留代码(使用reinterpret_cast)真的是一种很好的技术吗?

    下面的代码来自一篇关于C 面试问题的帖子here https www toptal com c plus plus interview questions 我从来不知道这种技术 尽管它声称是一种很好的技术 我的问题是 什么情况下需要使用它
  • -ffast-math 可以安全地用于典型项目吗?

    在回答我建议的问题时 ffast math 有评论指出这是危险的 我个人的感觉是 在科学计算之外 是可以的 我还假设严肃的金融应用程序使用定点而不是浮点 当然 如果你想在你的项目中使用它 最终的答案是在你的项目上测试它 看看它有多大影响 但
  • 从服务器下载图像(cUrl,但接受建议)C++

    我试图通过从服务器 网站 下载图像来设置旋转背景图像 并尝试使用curl 来执行此操作 但是在执行此操作方面取得了0 成功 我的代码的 缩短的 版本如下 我没有收到错误 但是 如何 临时 保存该图像以将其显示为背景 是否有图像 类型变量 或
  • 地图类容器的专用功能

    我想要专门为矢量和地图之类的容器设计一个函数模板 对于向量 我可以像下面那样做 但我不知道如何才能有一个专门版本的函数 该函数仅用于像地图这样的容器 include
  • 如何获取枚举数作为常量?

    From 枚举中定义的项目总数 https stackoverflow com questions 856154 total number of items defined in an enum 我发现我可以使用以下方法获取枚举数 Enum
  • 有关shared_ptr的竞态条件示例

    为什么没有竞争条件代码片段 https godbolt org z nEYPYqdqK below include
  • 以编程方式更新 Wifi 网络

    我正在尝试创建一个程序 当某个 wifi 网络在范围内时 该程序会连接到该网络 即使已经连接到另一个 wifi 也是如此 我在用着简单Wifi https github com DigiExam simplewifi 基本上效果很好 除了在
  • 如何将 dll 中包含的组件嵌入到 exe 中,以便它可以从内存运行?

    我正在尝试制作一个必须从内存运行的程序 通过Assembly Load bin 如上所述here http www codeproject com Articles 13897 Load an EXE File and Run It fro
  • 在编译输出中添加程序集绑定 (app.config)

    如果我编译应用程序 则会在输出中自动添加程序集绑定 具体的程序集绑定不在app config在 Visual Studio 中但在创建的应用程序配置中 有什么办法可以检查为什么会自动添加程序集绑定吗 选项AutoGenerateBindin
  • 如何在 Windows 上的 GCC 中链接 CS50 C 库

    我是 编程新手 一直在尝试使用以下命令编译我的代码MinGW https en wikipedia org wiki MinGW GCC 但我尝试包括CS50 https en wikipedia org wiki CS50 cs50 c
  • 在 C++ 中,为什么 const 也可以工作时编译器选择非常量函数? [复制]

    这个问题在这里已经有答案了 例如 假设我有一堂课 class Foo public std string Name m maybe modified true return m name const std string Name cons
  • C 编程中的 rand() 问题? [复制]

    这个问题在这里已经有答案了 可能的重复 为什么我总是用 rand 得到相同的随机数序列 https stackoverflow com questions 1108780 why do i always get the same seque
  • 对列表中的一系列整数求和

    假设我有一个这样的列表 List
  • 在 OSX 上检测 Objective C 或 C++ 中的文件夹访问(如 fs_usage 命令)

    我正在 OSX 上开发实时病毒扫描程序 OSX 的命令行命令fs usage可以通过以下方式确定文件夹访问权限 并且只能以 root 用户身份运行 fs usage w f pathname grep Users Documents Use
  • C 中的 2 个字符要短

    我有2个字符 Char 128和查尔2 如何将这些字符转为 Short640 in C 我试过了 unsigned short getShort unsigned char array int offset short returnVal
  • asio::this_coro::executor 的实现是什么

    在协程函数中 我们可以添加auto ex co await asio this coro executor 获取该协程的执行者 但当我想了解它的定义时 我发现了这个 Awaitable type that returns the execu
  • 对 Action 方法的两个并行 ajax 请求排队,为什么?

    我正在使用 ASP NET MVC 开发一个视频网站 我希望在我的应用程序中拥有的一项功能是转码视频 但由于转码过程可能非常耗时 我想向客户端用户展示该过程的进度 因此 我的架构是使用一个控制器操作来处理整个转码过程 并将其进度写入存储在服
  • 如何正确处置注入的DLL线程?

    我将一个 DLL 注入到目标进程中 以在玩 MMORPG 时充当助手 当前功能将按键转换为鼠标点击 因为 MMORPG 要求用户移动鼠标才能实现某些功能 这是我所鄙视的 假设我出于某种原因想要取消注入 DLL 我该怎么做呢 这个方法干净吗
  • 为什么在一行中使用这个 C++ 函数两次会导致编译错误?

    我在尝试在 Visual C 2010 中实现智能相等测试宏类型模板函数时遇到了一些麻烦 该函数与VS 中关于模板函数默认参数的错误 https stackoverflow com questions 10343177 why do i g

随机推荐