I tried make a Http request on Android 24 using code like
url = "http://10.0.2.2:8080/api/";
final HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod(method);
conn.setConnectTimeout(3000);
conn.setReadTimeout(5000);
conn.setDoOutput(true);
conn.setRequestProperty("Content-Type", "application/json;charset=utf-8");
conn.connect();
First I got an error like
java.io.IOException: Cleartext HTTP traffic to 10.0.2.2 not permitted
Then I added android:usesCleartextTraffic="true"
to AndroidManifest.xml as some solutions pointed out,
Now I get an error like
java.net.ConnectException: Failed to connect to /10.0.2.2:8080
The error gives no much useful information, I don't know how to search and solve this error. The server should be OK, for the code can pass on Android 23.
CodePudding user response:
First check did you added network permission in your manifest file.
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Just add the below code to your manifest file.
android:networkSecurityConfig="@xml/network_config"
Before you need to create a network rule
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
<domain-config cleartextTrafficPermitted="true">
<domain includeSubdomains="true">someDomain.com</domain>
</domain-config>
</network-security-config>
CodePudding user response:
Make sure you have added network permission in manifest
CodePudding user response:
Have you tried this server in your browser? Address 10.0.2.2 points to your machine's localhost
. If you open http://localhost:8080
(on computer runnig the emulator) you may get more info about the error. It's worth mentioning, that next to clearTraffic manifest flag, you now need to specify Network security configuration as well:
<application
....
android:networkSecurityConfig="@xml/network_rules"
....
Network rules xml:
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
<domain-config cleartextTrafficPermitted="true">
<domain includeSubdomains="true">someDomain.com</domain>
</domain-config>
</network-security-config>
CodePudding user response:
Looks like you are using http request. You can use https request to avoid this issue.Try with this for http request.
Put the below line in android manifest under application tag
android:networkSecurityConfig="@xml/network_security_config"
Create xml file inside res/xml/network_security_config.xml
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
<domain-config cleartextTrafficPermitted="true">
<domain includeSubdomains="true">your domain</domain>
</domain-config>
</network-security-config>