使用Pull解析XML,使用真机调试的时候遇到两个报错:
java.net.SocketTimeoutException: connect timed out
java.net.ConnectException: Failed to connect to
找了很多资料,终于解决这个问题!
解决方案:
private static final long READ_TIMEOUT = 60000;
//写入超时为60s
private static final long WRITE_TIMEOUT = 60000;
//连接超时为60s
private static final long CONNECT_TIMEOUT = 60000;
OkHttpClient client = new OkHttpClient.Builder()
.readTimeout(READ_TIMEOUT, TimeUnit.MILLISECONDS)
.writeTimeout(WRITE_TIMEOUT, TimeUnit.MILLISECONDS)
.connectTimeout(CONNECT_TIMEOUT, TimeUnit.MILLISECONDS)
.build();
Request request = new Request.Builder()
.url("http://192.168.43.145/get_data.xml")
.build();
解决方案:
在res目录下找到xml目录(如果没有xml目录则新建一个),然后新建一个文件,名为network_security_config.xml
内容如下:domain标签中要填你本机的ip地址,可以打开命令行输入ipconfig查看
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
<domain-config cleartextTrafficPermitted="true">
<domain includeSubdomains="true">Your URL(ex: 127.0.0.1)</domain>
</domain-config>
</network-security-config>
启用 android:usesCleartextTraffic
<?xml version="1.0" encoding="utf-8"?>
<manifest ...>
<uses-permission android:name="android.permission.INTERNET" />
<application
...
android:usesCleartextTraffic="true"
...>
...
</application>
</manifest>
<?xml version="1.0" encoding="utf-8"?>
<manifest android:targetSandboxVersion="1">
<uses-permission android:name="android.permission.INTERNET" />
...
</manifest>
如果还是不行,那么很大的原因是因为:你的手机和电脑没在同一个局域网。一定要让你的电脑和你的手机连接同一个局域网或者wifi!!!(我就是犯了这个错误,查找原因花了一下午)
最后希望大家都能成功解决这个问题!!!