how to add proxy support to boost::asio?

2020-02-10 05:52发布

问题:

In my desktop application I added access to various internet resources using boost::asio. All i do is sending http requests (i.e to map tile servers) and read the results. My code is based on the asio sync_client sample.

Now i get reports from customers who are unable to use these functions as they are running a proxy in their company. In a web browser they can enter the address of their proxy and everything is fine. Our application is unable to download data.

How can i add such support to my application?

回答1:

I found the answer myself. It's quite simple:

http://www.jmarshall.com/easy/http/#proxies gives quite a brief and clear description how http proxies work.

All i had to do is add the following code to the asio sync_client sample sample :

std::string myProxyServer = ...;
int         myProxyPort   = ...;

void doDownLoad(const std::string &in_server, const std::string &in_path, std::ostream &outstream)
{
    std::string server      = in_server;
    std::string path        = in_path;
    char serice_port[255];
    strcpy(serice_port, "http");

    if(! myProxyServer.empty())
    {
        path   = "http://" + in_server + in_path;
        server = myProxyServer;
        if(myProxyPort    != 0)
            sprintf(serice_port, "%d", myProxyPort);
    }
    tcp::resolver resolver(io_service);
    tcp::resolver::query query(server, serice_port);

...


回答2:

It seems that sample is merely a show-off of what Boost ASIO can be used for but is likely not intended to be used as-is. You should probably use a complete library that handles not only HTTP proxies, but also HTTP redirects, compression, and so on.

HTTP is a complex thing: without doing so, chances are high that you will get news from another client soon with another problem.

I found cppnetlib which looks promising and is based on Boost ASIO not sure it handles proxies though.

There is also libcurl but I don't know if it can easily be integrated with Boost ASIO.