'.Net MAUI Android can't talk to API localhost
I've downloaded the latest sample MAUI here: https://github.com/microsoft/dotnet-podcasts and copied the exact way they make requests but I can't get passed an 'unexpected end of stream error':
System.Net.WebException: unexpected end of stream on com.android.okhttp.Address@4c288121
---> Java.IO.IOException: unexpected end of stream on com.android.okhttp.Address@4c288121
I'm initialising the HttpClient in the MauiProgram.cs via the AddHttpClient factory method like so (note the different IP address for Andorid):
public static string Base = DeviceInfo.Platform == DevicePlatform.Android ? "http://10.0.2.2" : "https://localhost";
public static string APIUrl = $"{Base}:7096/api/";
builder.Services.AddHttpClient<DishClient>(client => { client.BaseAddress = new Uri(APIUrl); });
I've included the following android:networkSecurityConfig in the AndroidManifest.xml (which allows http traffic):
<network-security-config>
<base-config cleartextTrafficPermitted="true">
<trust-anchors>
<certificates src="system" />
</trust-anchors>
</base-config>
</network-security-config>
The solution in Xamarin it seems is to use AndroidClientHandler but this is in a deprecated library that I can't use in MAUI, and there's no reference to it in the linked solution that works.
Things I've tried:
using Https: I've followed the guide here: https://docs.microsoft.com/en-us/xamarin/cross-platform/deploy-test/connect-to-local-web-services#bypass-the-certificate-security-check but I still get certificate errors:
System.Net.WebException: java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.
---> Javax.Net.Ssl.SSLHandshakeException: java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.
I've also tried this
handler.ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator;
but get an error
System.PlatformNotSupportedException: Operation is not supported on this platform
It's been 4 days non-stop and i've gone through every conceivable setting in the working solution and can't find any differences. Any ideas?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
