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
- If you've not already done so, clone the Mongoose Library repo
$ git clone https://github.com/cesanta/mongoose
- Build the example, this will also start Mongoose and the connection process
$ cd mongoose/examples/http-proxy-client $ make clean all
- The HTML for the very first web page at CERN will be printed
Build with TLS support
The makefile will take care of this if you pass the proper argument.
- For openSSL:
$ make clean all SSL=OPENSSL
- For mbedTLS:
$ make clean all SSL=MBEDTLS
- Run the example, providing a valid HTTPS-capable proxy address and port, and an
https://
host URL$ ./example PROXY:PORT https://HOST/
For more information on building 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 validHost
header using the mg_url_host() and mg_url_port() functions. We then send aCONNECT
request to the proxy using mg_printf(). Note that we initialize TLS if the host URL ishttps://
.
- 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 simpleGET
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.