HTTP proxy client

Overview

This tutorial will show you how to use Mongoose as an HTTP client in places where connections must be done through a proxy. The task is similar to what has been described in the HTTP client tutorial, though this time instead of directly connecting to our desired host, we must connect to the specified proxy and handle our request to it.

Build and run

Follow the Build Tools tutorial to setup your development environment. Then start a command prompt / terminal and enter the following (first argument is the proxy URL, second is the target website URL):

git clone https://github.com/cesanta/mongoose
cd mongoose/tutorials/http/http-proxy-client
make ARGS="http://1.1.1.1:1234 http://info.cern.ch/"

Done! The full source code for this tutorial is at https://github.com/cesanta/mongoose/tree/master/tutorials/http/http-proxy-client

If your URL is https://, then make sure to build this example with TLS support - see below

TLS support

Check the "How to build" section of the TLS tutorial for specific information on building options for your OS

For more information on developing TLS clients, check the TLS tutorial

How it works

  • We create a client connection to the proxy, using the mg_http_connect() function. The connection handler will process the respective events
  • When we receive an MG_EV_CONNECT event, we extract the hostname and port number from the URL to form a valid Host header using the mg_url_host() and mg_url_port() functions. We then send a CONNECT request to the proxy using mg_printf(). Note that we initialize TLS if the host URL is https://.
  • When we receive our first MG_EV_READ event, we are connected to the proxy. We set a flag to ignore all subsequent events like this, and send a simple GET request, using the mg_url_uri() function to craft the URI part.
  • Finally, when we get an MG_EV_HTTP_MSG event, the full page content has been downloaded, we print it.

Note that we are not performing retries on connection failure nor any error handling, check the error handling tutorial for more information on this subject.

Browse latest code