android - .Net MAUI Android 无法与 API localhost 对话

标签 android .net maui .net-maui

我在这里下载了最新的示例 MAUI:https://github.com/microsoft/dotnet-podcasts并复制了他们提出请求的确切方式,但我无法通过“意外的流错误结束”:

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
我正在初始化 HttpClient通过 AddHttpClient 在 MauiProgram.cs 中像这样的工厂方法(注意Andorid的不同IP地址):
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); });
我已包含以下 android:networkSecurityConfig在 AndroidManifest.xml(允许 http 流量)中:
<network-security-config>
  <base-config cleartextTrafficPermitted="true">
        <trust-anchors>
            <certificates src="system" />
        </trust-anchors>
    </base-config>
</network-security-config>
Xamarin 中的解决方案似乎是使用 AndroidClientHandler但这是在一个已弃用的库中,我不能在 MAUI 中使用,并且在有效的链接解决方案中没有引用它。
我试过的东西:
使用 Https:我已经按照这里的指南进行操作:https://docs.microsoft.com/en-us/xamarin/cross-platform/deploy-test/connect-to-local-web-services#bypass-the-certificate-security-check但我仍然收到证书错误:
   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.
我也试过这个
handler.ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator; 
但得到一个错误
System.PlatformNotSupportedException: Operation is not supported on this platform
已经连续 4 天了,我已经完成了工作解决方案中所有可以想象的设置,但找不到任何差异。有任何想法吗?

最佳答案

@Jimmy 在您的代码中,您将 URL 更改为 "https://localhost""http://10.0.2.2"当你在安卓上运行时。在这两种情况下,您都在端口 调用 API。 7096 :public static string APIUrl = $"{Base}:7096/api/"; .对于 android,您使用的是 HTTP 协议(protocol),而在所有其他情况下,您使用的是 HTTPS。
我假设你的服务器监听 HTTP 小号 仅在端口 7096 上,而不是 HTTP。也许这会导致您的问题。
另一个问题可能是您的服务只绑定(bind)到 localhost但不是您的 IP 地址(您可以在 API 的 launchsettings.json 中查找)。
另一个问题可能是您的防火墙不允许端口 7096 上的传入流量。您也应该检查这一点,因为在 Windows 上运行时您没有越过机器边界。但是,在 Android 模拟器上运行时,您可以进行跨机通信。

关于android - .Net MAUI Android 无法与 API localhost 对话,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72313635/

相关文章:

android - "ActionBar not available for TabGroup"是什么意思?

android - fragment 中的 AdMob 横幅

c# - 如何为 System.Windows.Fontstyle 设置粗体字样?

.net - 是否可以在.NET中捕获访问冲突异常?

c# - HTTPOnly 将 cookie 过期时间设置为 session

maui - 使用 BoolToObjectConverter 设置 Color 属性

c# - TabbedPage 无法在使用 MAUI 的 iOS 上工作,而是显示空白页面

android - 导航栏中的后退按钮不起作用?

android - 无法在android中运行opencv示例

.Net Maui 将 Assets 复制到 appData