47

解决 Android 28 不能请求 HTTP 接口的问题 · Issue #5 · collinxz-coder/blog · GitH...

 4 years ago
source link: https://github.com/collinxz-coder/blog/issues/5?
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Comments

从Android 9(API级别28)开始,默认情况下禁用明文支持。

所以我们要请求 HTTP 接口则需要多做一些配置来开启 HTTP 的支持。

android:usesCleartextTraffic

在 Android 项目的 app/main/AndroidManifest.xml 的 application 配置中加上 android:usesCleartextTraffic="true":

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
  package="xxxx">
  <application
    ...
    android:usesCleartextTraffic="true"    // 添加这一行
    ...
  >
      ...
  </application>
</manifest>

这个方式的优点是配置简单,但缺点是全局所有的 API 都支持 HTTP。出于安全起见,我们应该手动配置支持 HTTP 的白名单。这就是我们说的第二种方式。

详细内容参见谷歌安卓开发文档网络安全配置章节。我们这只简单介绍配置步骤:

  1. 添加网络配置文件: app/main/res/xml/network_security_config.xml
  2. 将以下内容添加到刚添加的文件中:
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <domain-config cleartextTrafficPermitted="true">
        <domain includeSubdomains="true">需要支持 HTTP 的域名</domain>
    </domain-config>
</network-security-config>
  1. app/main/AndroidManifest.xml 文件中使用刚添加的配置文件:
<application
  ...
  android:networkSecurityConfig="@xml/network_security_config"
  ...
>

</application>

第二种方式我在开发工作中发现不支持 ip 地址。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK