Android访问自己的Tomcat出现java.net.ConnectException: localhost/127.0.0.1:8080
NetworkSecurityConfig: No Network Security Config specified, using platform default
在浏览器可以访问都是可以成功,为什么真机和模拟器出现错误!权限什么的都有,为什么一直失败!
1、如果在真机上时,可以用pc的真实ip
代替127.0.0.1
和localhost
</br>
2、如果在模拟器上,可以用10.0.2.2
代替127.0.0.1
和localhost
</br>
模拟器默认把127.0.0.1和localhost当做本身了,在模拟器上可以用10.0.2.2代替127.0.0.1和localhost
new Thread(new Runnable() {
@Override
public void run() {
URL url;
try {
//真机使用电脑真实ip做为host 我的电脑ip为192.168.1.111
url = new URL("http://192.168.1.111:8080/student/getAllStudent");
//模拟器使用 10.0.2.2 作为host
url = new URL("http://10.0.2.2:8080/student/getAllStudent");
HttpURLConnection connection= (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.connect();
if (connection.getResponseCode()==200){
InputStream inputStream = connection.getInputStream();
BufferedReader bufferedReader=
new BufferedReader(
new InputStreamReader(inputStream,"utf-8"));
String line;
final StringBuilder sb=new StringBuilder();
while ((line=bufferedReader.readLine())!=null){
sb.append(line);
}
Log.e(TAG, "run: 请求结果:"+sb.toString() );
runOnUiThread(new Runnable() {
@Override
public void run() {
textView.setText(sb.toString());
}
});
}else {
Log.e(TAG, "run: 请求失败!" );
}
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();