Unable connect to a HTTP URL in Android 10

谁说胖子不能爱 提交于 2021-02-05 06:57:05

问题


I am using a http://something API for the login process. But could't get a hit on API in Android 10. For rest of the version, the API is working fine. First of all, I was getting SocketTimeoutException. Then I tried following solutions.

1) Added below attribute to <application> in Manifest.

android:usesCleartextTraffic="true"

Result: Still getting SocketTimeoutException.

2) Then I added networkSecurityConfig:

<network-security-config>
<domain-config cleartextTrafficPermitted="true">
    <domain includeSubdomains="true">project.dev.company:6001/</domain>
    <trust-anchors>
        <certificates src="system"/>
    </trust-anchors>
</domain-config>
</network-security-config>

Result : UnknownServiceException : CLEARTEXT communication to project.dev.company:6001/ is not permitted by network security policy.

3) Also tried permitting CLEARTEXT in <base-config>. Still getting SocketTimeoutException.

How can I permit my app to access a HTTP connection from Android 10? I am using Retrofit2 for network calling.


回答1:


Use this codes in your xml file

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

and use this codes in manifest:

android:usesCleartextTraffic="true"
android:networkSecurityConfig="@xml/network_security_configuration"

dont need any "/" and port in domain,just use like me

Edited:

you can use IP of your api host,like this:

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


来源:https://stackoverflow.com/questions/58407173/unable-connect-to-a-http-url-in-android-10

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!