如何解决Android P DownloadManager出现“不允许将明文HTTP流量发送到127.0.0.1”?

26

我已经按照这里的建议自定义了网络安全配置并将其包含在我的清单文件中。

res/xml/network_security_config.xml:

  <?xml version="1.0" encoding="utf-8"?>
  <network-security-config>
  <domain-config cleartextTrafficPermitted="true">
    <domain includeSubdomains="true">127.0.0.1</domain>
    <domain includeSubdomains="true">localhost</domain>
  </domain-config>
  </network-security-config>

这是我的Android.manifest文件中的内容:

    <application android:icon="@drawable/icon" 
             android:allowBackup="false"
             android:usesCleartextTraffic="true"
             android:networkSecurityConfig="@xml/network_security_config"
             android:label="@string/app_name"
             android:theme="@style/AppTheme"
             android:persistent="true" >
即使进行了这些更改,当尝试通过HTTP与127.0.0.1通信时,我在logcat中看到了这个消息:
08-09 10:50:34.395 30791  3607 D NetworkSecurityConfig: Using Network Security Config from resource network_security_config debugBuild: true
08-09 10:50:34.397 30791  3607 D NetworkSecurityConfig: Using Network Security Config from resource network_security_config debugBuild: true
08-09 10:50:34.401 30791  3607 W DownloadManager: [647] Stop requested with status HTTP_DATA_ERROR: Cleartext HTTP traffic to 127.0.0.1 not permitted
08-09 10:50:34.402 30791  3607 D DownloadManager: [647] Finished with status WAITING_TO_RETRY

编辑:更新(2018年8月21日)在“修复”此问题后,似乎安装应用程序的几个小时后,DownloadManager神秘地停止接受明文HTTP。

我无法解释发生了什么。如果我重新启动设备,则一段时间内事情会很好,然后DownloadManager再次拒绝使用明文。我认为这是一个Android P的错误,希望能得到解决。

编辑2:更新(2019年1月17日),我的Pixel2现在运行Android 9,并具有来自2019年1月5日的补丁,我不再遇到此问题(至此)。我猜想此问题已在自8月以来的某个补丁中得到解决。


1
在 <network-security-config> 中添加 <base-config cleartextTrafficPermitted="true"/> ... 并用 </base-config> 结束。 - ares777
1
@user3344236 将 domain-config 替换为 base-config 即可解决问题!请将您的回复作为答案提交,我会标记为已接受。 - spartygw
1
Spartygw,针对“EDIT: Update (21 Aug 2018)”的回应,我和你看到了相同的情况。它可以工作,但是几个小时后就停止工作。为了暂时解决这个问题,我可以强制退出下载管理器应用程序,重新启动我的应用程序并尝试再次下载,这样它就会工作。我同意你的看法。这似乎是Android P的代码中Download Manager中的一个bug。 - hokielife
3
我已向Google提交了一个关于你的更新(2018年8月21日)的问题。https://issuetracker.google.com/issues/114143692 - LeonLu
@LeonLu,太好了!我甚至不知道如何将此问题提出,所以非常感谢你。 - spartygw
3个回答

48
创建一个XML文件res/xml/network_security_config.xml。
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <base-config cleartextTrafficPermitted="true" />
</network-security-config>

在你的AndroidManifest.xml文件中,将这个文件作为你的应用程序标签的参考。例如:

android:networkSecurityConfig="@xml/network_security_config"

1
正如你已经知道的那样,该结构是XML,关闭标签的标准格式为</。 - ares777
感谢您关于闭合标签的课程!现在请从<base-config cleartextTrafficPermitted="true" />中删除尾随的/ ;) - John Smith
2
不需要,因为它不是一个节点John Smith :)) 通常使用HTML的关闭方式。请再次阅读链接。 - ares777
1
经过尝试多种方法,以上代码解决了明文通信问题。非常感谢。 - Loganathan
不知道为什么对我不起作用,你有什么想法吗?是否需要添加一些东西? - Jalpesh
显示剩余6条评论

0

打开清单文件 输入图像描述

添加 android:usesCleartextTraffic="true" 输入图像描述


-1

将 BASE_URL 的协议从 http://...替换为https://


请解释为什么这个替换可以回答这个问题。 - Sfili_81

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