通过C#使用C++boost.asio Rest API

Consume C++ boost.asio Rest API by C#

本文关键字:Rest API asio C++boost 使用 通过      更新时间:2023-10-16

我有一个正在返回正确数据的rest API,问题是当我消费来自C#代码时。其返回的坏网关

以下是我的服务器的两个代码

#include <ctime>
#include <iostream>
#include <string>
#include <boost/asio.hpp>
using boost::asio::ip::tcp;
using namespace std;
std::string make_daytime_string()
{
        using namespace std; // For time_t, time and ctime;
        time_t now = time(0);
        return ctime(&now);
}
int main()
{
        try
        {
                boost::asio::io_service io_service;
                tcp::acceptor acceptor(io_service, tcp::endpoint(tcp::v4(), 1313));
                for (;;)
                {
                        cout << "listening for socket" << endl;
                        tcp::socket socket(io_service);
                        acceptor.accept(socket);

                        cout << "listening for socket" << endl;
                        std::string message = make_daytime_string();
                        message = "I am a response from rest service baby !!!";
                        boost::system::error_code ignored_error;
                        boost::asio::write(socket, boost::asio::buffer(message), ignored_error);
                }
        }
        catch (std::exception& e)
        {
                std::cerr << e.what() << std::endl;
        }
        return 0;
}

为了消费它,我有下面的c#代码

WebRequest req = WebRequest.Create("http://192.168.17.85:1313/");
req.Method = "GET";
WebResponse rep = req.GetResponse();

我似乎不理解这个问题,因为它很容易从网络浏览器中消费,但它从这个代码中返回502(坏网关)。

您只是在向套接字中写入,响应中没有HTTP,浏览器是"好";足以发现这种问题。您需要使用HTTP协议格式化代码。

请检查HTTP 1.1的RFC 2616(我认为这是最常见的版本)。