HTTP proxy client
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/examples/http-proxy-client make ARGS="http://126.96.36.199:1234 http://info.cern.ch/"
Done! The full source code for this tutorial is at examples/http-proxy-client.
If your URL is https://, then make sure to build this example with TLS support - see below
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_CONNECTevent, we extract the hostname and port number from the URL to form a valid
Hostheader using the mg_url_host() and mg_url_port() functions. We then send a
CONNECTrequest to the proxy using mg_printf(). Note that we initialize TLS if the host URL is
- When we receive our first
MG_EV_READevent, we are connected to the proxy. We set a flag to ignore all subsequent events like this, and send a simple
GETrequest, using the mg_url_uri() function to craft the URI part.
- Finally, when we get an
MG_EV_HTTP_MSGevent, 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.