gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 00:01:50 34 4
gpt4 key购买 nike

我在这里下载了最新的示例 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/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com