Android应用程序无法发送HTTP请求

时间:2020-10-05 08:09:43

标签: java android retrofit httprequest retrofit2

我有一个Android应用程序,该应用程序使用Retrofit发出http请求(POST)并进一步评估传入数据。 我的测试电话(Samsung J5 P)中的应用程序运行正常,它可以连接并发送请求。但是,尝试在两部不同的手机上同时操作该应用程序时,另一部手机上的应用程序以某种方式无法发送请求(连接失败时,改装将调用onFailure方法)。我已启用所有权限,但问题似乎发生了。

此外,我已经将服务器托管在桌面(本地主机)上,并且确保两个设备都连接到同一网络。

什么可能导致此问题?谢谢。

2 个答案:

答案 0 :(得分:0)

在res / xml目录中创建网络配置文件

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

然后在清单的应用程序标签中添加android:networkSecurityConfig="@xml/network_security_config"

答案 1 :(得分:0)

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

也可以看看-https://koz.io/android-m-and-the-war-on-cleartext-traffic/

Codelabs的解释-https://codelabs.developers.google.com/codelabs/android-network-security-config/index.html

Option 1 -

First try hitting the URL with "https://" instead of "http://"

Option 2 -

Create file res/xml/network_security_config.xml -

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <domain-config cleartextTrafficPermitted="true">
        <domain includeSubdomains="true">api.example.com(to be adjusted)</domain>
    </domain-config>
</network-security-config>
AndroidManifest.xml -

<?xml version="1.0" encoding="utf-8"?>
<manifest ...>
    <uses-permission android:name="android.permission.INTERNET" />
    <application
        ...
        android:networkSecurityConfig="@xml/network_security_config"
        ...>
        ...
    </application>
</manifest>
Option 3 -

android:usesCleartextTraffic Doc

AndroidManifest.xml -

<?xml version="1.0" encoding="utf-8"?>
<manifest ...>
    <uses-permission android:name="android.permission.INTERNET" />
    <application
        ...
        android:usesCleartextTraffic="true"
        ...>
        ...
    </application>
</manifest>

 android:targetSandboxVersion can be a problem too -

According to Manifest Docs -

android:targetSandboxVersion

The target sandbox for this app to use. The higher the sandbox version number, the higher the level of security. Its default value is 1; you can also set it to 2. Setting this attribute to 2 switches the app to a different SELinux sandbox. The following restrictions apply to a level 2 sandbox:

The default value of usesCleartextTraffic in the Network Security Config is false.
Uid sharing is not permitted.
So Option 4 -

If you have android:targetSandboxVersion in <manifest> then reduce it to 1

AndroidManifest.xml -

<?xml version="1.0" encoding="utf-8"?>
<manifest android:targetSandboxVersion="1">
    <uses-permission android:name="android.permission.INTERNET" />
    ...
</manifest>