A simple way to proxy local HTTP endpoints for Android Development

When developing Android apps, testing local backend changes often involves running a local server. Traditionally, swapping the URL in your app to point to this local server (typically using HTTP) was quite easy. However, Android 9 (Pie) and later introduced a (welcome) security change: HTTP traffic is blocked by default. Trying to connect to an HTTP endpoint with your Android app will fail with the following error message:

 REQUEST http://127.0.0.1/XYZ failed with exception: java.net.UnknownServiceException: CLEARTEXT communication to 127.0.0.1 not permitted by network security policy

There are workarounds for testing a local running app with a local running server. You can configure your local server for HTTPS. This requires additional setup and might not be ideal for quick testing. Also, you can allow HTTP temporarily. While possible, it's a less secure approach you wouldn't want this to slip into production.

Thankfully, there's an easier solution: dev tunnels from Microsoft.

What are dev tunnels?

Dev tunnels are primarily designed to securely expose your local development environment (localhost) to the internet. This allows you to easily test and debug web apps and webhooks from anywhere. But in our case, it can be leveraged to create a secure HTTPS proxy for your local HTTP server with minimal code changes.

Usage

After installing, just run your local server. Ensure your local development server is up and running, noting down the port it's using (e.g., 8000). Then open a terminal and run the following command, replacing <port> with the actual port your server is on:

devtunnel host -p <port> --allow-anonymous

The --allow-anonymous flag allows anyone on the internet to access the tunnel.

The command will output a message indicating the dev tunnel proxy URL. Use this in your Android app instead of the original HTTP address pointing to your local server. Your app will now communicate securely with your local server through the tunnel.

Security considerations

Remember that dev tunnels route traffic through the internet. This raises security concerns if you're dealing with sensitive data. It's best suited for testing non-critical data during development.

Beyond local development

While this blog post focuses on local development, dev tunnels offer additional benefits. More specifically, you can use it for remote collaboration to share your local development environment with colleagues for testing and feedback, even if they're not on your local network.

Dev tunnels offer a convenient and secure way to proxy local HTTP traffic for your Android app development on Android 9 (Pie) and later with minimal configuration and code changes (without compromising security best practices).

Happy coding!