如何在 Xamarin Android 中修复“不允许使用明文 HTTP 流量到 x”的问题

11

我的应用程序存在问题"Cleartext HTTP traffic to x not permitted."

我已经尝试在清单文件中添加android:usesCleartextTraffic="true"。但我想将"android:usesCleartextTraffic"标志更改为"false",以防止发送未加密的流量。

如何解决这个问题?


您想以编程方式禁用 usesCleartextTraffic 吗? - ColeX
我遇到了“不允许获取x的明文HTTP流量”问题。如何在不将android:usesCleartextTraffic设置为true的情况下解决此问题? - SoftDev
请查看 https://dev59.com/CrLma4cB1Zd3GeqPUglb#54827498。 - ColeX
你是怎么解决这个问题的,请 @SoftDev? - sanepete
4个回答

39

如果您想迁移到没有 AssemblyInfo.csMAUI,您可能需要在 Platforms/Android/MainApplication.cs 中的应用程序属性中添加 UsesCleartextTraffic

#if DEBUG                                   // connect to local service on the
[Application(UsesCleartextTraffic = true)]  // emulator's host for debugging,
#else                                       // access via http://10.0.2.2
[Application]                               
#endif
public class MainApplication : MauiApplication
{
    ...
}

18
您可以用一行代码解决这个问题。 在您的 Android 项目中,打开属性下的 AssemblyInfo.cs,并添加以下代码:
[assembly: Application(UsesCleartextTraffic = true)]

4
如果你只想在调试版本中允许这种行为,我建议你将其包装在 #if DEBUG#endif 中。请注意不要改变原意。 - Mike

18
在 Maui 中,展开 Platforms/Android 并编辑 MainApplication.cs。
在顶部附近将 "[Application]" 替换为 "[Application(UsesCleartextTraffic = true)]"。

谢谢,我特别在寻找这个。 - YaRmgl
3
基本上是我的答案的复制,但对于严肃应用程序的发布版本,您绝对希望限制网络连接仅使用TLS。如果您上传一个仍允许http连接的应用程序到GooglePlay,它可能会降低评论评级。因此,我建议使用“#if DEBUG”。 - thomiel
你是我的英雄!节省了时间。一直在寻找它。 - Serique

1
假设您正在访问一个不支持HTTPS的服务器,那么您可以在网络安全配置中创建异常。您可以创建一个名为net_sec_conf.xml的文件,内容如下:
<?xml version="1.0" encoding="utf-8" ?>
<network-security-config>
  <base-config cleartextTrafficPermitted="false">
    <trust-anchors>
      <certificates src="system" />
    </trust-anchors>
  </base-config>
  <domain-config cleartextTrafficPermitted="true">
    <domain includeSubdomains="true">api.example.org</domain>
    <trust-anchors>
      <certificates src="system" />
    </trust-anchors>
  </domain-config>
</network-security-config>

然后在清单文件中添加这一行:

android:networkSecurityConfig="@xml/net_sec_conf"

(假设您已将文件放入xml文件夹中)。 这样,明文HTTP流量仅允许指定域。 当然,如果服务器支持HTTPS,则只需将URL“http:// ...”更改为“https:// ...”。

我尝试过类似的方法,但无法找出如何将net_sec_conf.xml添加到构件中。在apk文件中有一个res/xml文件夹,但它并没有包含添加的文件net_sec_conf.xml。@Mordecai的解决方案以及Mike的调试注释对我很有帮助。 - Vering

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接