HttpClient and Proxy
Nowadays it’s hard to find a mobile application which would function without backend server. As a Xamarin developer, you must have repeatedly created a class to encapsulate network communication setup like BaseUri, security settings, logging etc. So you probably have written a code, at its core similar to this one:
HttpService is developed with best code practices in mind: an
HttpClient instance is created once and reused for all requests, asynchronous programming patterns are applied and a cancellation mechanism is implemented.
Even after taking a closer look it is difficult to notice a bug here. After the application is released, a few users might complain that the app does not seem to recognize the network settings or have internet access at all. By the way, traffic sniffering tools like Fiddler won’t work as well.
The problem is, out of the box the
System.Net.Http.HttpClient does not respect the system’s proxy setup.
In order to fix that, proxy settings should be read on each platform and passed to
Let’s start with declaring an interface
and implementing it on each platform:
We are done with platform-specific code. Now we should fix shared code where
HttpClient was created by injecting
IProxyInfoProvider and applying the proxy settings.
Changing the code sample from the top,
The platform implementation of
IProxyInfoProvider may be registered in IoC container of your choice or provided by any other dependency inversion technique you prefer.