Search code examples
c#c++restboost

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


I have a rest API that is returning proper data, the problem is when i am consuming is from a C# code. Its returning bad gateway

following are my both codes for server

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

and for consuming it i have the following c# code

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

I dont seem to understand the problem, because it is easily consumed from the web browser but its returning 502 (Bad Gateway) from this code.


Solution

  • You are simply writing into a socket, there is no HTTP in your response, browsers are "good" enough to detect this kind of problem. You need to format your code using HTTP protocol.

    Please check the RFC 2616 for HTTP 1.1 (I think this is the most common version).