-
Notifications
You must be signed in to change notification settings - Fork 14
Configuring HttpClient
- [MAUI]
- [IHttpClientFactory]
To provide access to your local computer services during development, you should configure your MAUI Android environment. On Android, a different type of message handler implementation is necessary, than on other platforms:
#if ANDROID
internal sealed class DevelopmentAndroidMessageHandler : Xamarin.Android.Net.AndroidMessageHandler
{
protected override Javax.Net.Ssl.IHostnameVerifier GetSSLHostnameVerifier(Javax.Net.Ssl.HttpsURLConnection connection)
=> new CustomHostnameVerifier();
private sealed class CustomHostnameVerifier : Java.Lang.Object, Javax.Net.Ssl.IHostnameVerifier
{
public bool Verify(string hostname, Javax.Net.Ssl.ISSLSession session)
{
return
Javax.Net.Ssl.HttpsURLConnection.DefaultHostnameVerifier.Verify(hostname, session)
|| hostname == "10.0.2.2" && session.PeerPrincipal?.Name == "CN=localhost";
}
}
}
#endif
In your MAUI application, open your MauiProgram.cs file and add the follosing code:
#if DEBUG
private static HttpMessageHandler GetLocalhostHandler()
{
#if ANDROID
DevelopmentAndroidMessageHandler handler = new DevelopmentAndroidMessageHandler();
#else
HttpClientHandler handler = new HttpClientHandler();
#endif
handler.ServerCertificateCustomValidationCallback = (message, cert, chain, errors) =>
{
if (cert != null && cert.Issuer.Equals("CN=localhost")) return true;
return errors == System.Net.Security.SslPolicyErrors.None;
};
return handler;
}
#endif
This code snippet handles your Windows, iOS, Android, TizenOS environment, when you need to instantiate a HttpClient for API calls. When configuring the OpenAI options, provide the factory method on the proper way:
builder.Services.AddForgeOpenAI(options => {
options.AuthenticationInfo = builder.Configuration["OpenAI:ApiKey"]!;
#if DEBUG
options.HttpMessageHandlerFactory = GetLocalhostHandler();
#endif
});
How to override the setup and settings of built-in IHttpClientFactory. This is useful, for example, if you implement resilement HTTP requests, retry policy or circuit-breaker with Polly
https://learn.microsoft.com/en-us/dotnet/fundamentals/networking/http/httpclient-guidelines