【问题标题】:How to fix 'Cleartext HTTP traffic to x not permitted' in xamarin android如何在 xamarin android 中修复“不允许到 x 的明文 HTTP 流量”
【发布时间】:2021-04-13 08:12:41
【问题描述】:

我的应用程序出现问题,不允许到 x 的 Cleartext HTTP 流量。

我已经尝试将 android:usesCleartextTraffic="true" 放入我的清单中。但我想将“android:usesCleartextTraffic”标志更改为“false”以防止发送未加密的流量。

如何解决?

【问题讨论】:

  • 您想以编程方式禁用usesCleartextTraffic 吗?
  • 我将 Cleartext HTTP 流量发送到 x 不允许的问题。如何在清单文件中不启用 android:usesCleartextTraffic 为 true 的情况下解决此问题
  • 你是怎么解决这个问题的,请@SoftDev?

标签: http xamarin.forms https xamarin.android cleartext


【解决方案1】:

你可以用一行代码解决这个问题。 在你的android项目的properties下打开AssemblyInfo.cs并添加以下代码:

[assembly: Application(UsesCleartextTraffic = true)]

【讨论】:

  • 我可能还建议将其包装在 #if DEBUG#endif 中,以防您只想在调试版本中允许此行为。
【解决方案2】:

假设您正在访问不支持 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 的调试评论对我有用。
猜你喜欢
  • 1970-01-01
  • 2019-07-16
  • 2020-02-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多