我当前正在构建一个应用程序,该应用程序必须使用GET或POST查询访问我的REST服务,但是在尝试通过输入IPv4地址连接到主机时有时(并非总是如此,仅有时不是),出现以下错误:
2019-11-14 14:01:22.279 30991-31089/com.example.mc.practical_assigment E/CONNECT ERROR GET USER: class java.net.NoRouteToHostException
2019-11-14 14:01:22.279 30991-31089/com.example.mc.practical_assigment E/CONNECT ERROR GET USER: [Ljava.lang.StackTraceElement;@840301f
2019-11-14 14:01:22.279 30991-31089/com.example.mc.practical_assigment E/CONNECT ERROR GET USER: Host unreachable
这是给我错误的行,我的项目在这里刹车:
urlConnection.getOutputStream();
使用Android Studio模拟器PIXEL 2 XL API 28时,永远不会出错,始终会建立连接,但是在我的真实设备OnePlus ONEPLUS A3003上,有时程序无法获得主机响应。
我以前使用Postman测试过REST服务,因为有时它每次都可以在我的应用程序和Postman中工作,所以我知道URL路径是有效的。
我也尝试使用我的移动热点,它仍然不能解决问题。
我试图从计算机上关闭防火墙,以免以任何方式过滤数据。
在我看来,我的问题出在手机中,但我不知道是出于什么原因,因为我无法弄清错误的发生方式。
还有其他尝试吗?
也许问题出在使用Android Studio时是那种连接类型,我应该尝试使用其他代码。
我的代码的整个示例:
try {
url = new URL("http://" + BaseAddress.getAddress() + ":8084/ACME_Electronic_Supermarket/webresources/acme/user/login");
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty("Content-Type", "application/json");
urlConnection.setUseCaches (false);
OutputStream os = urlConnection.getOutputStream(); //point of failure
DataOutputStream outputStream = new DataOutputStream(os);
String payload = gson.toJson(user);
outputStream.writeBytes(payload);
outputStream.flush();
outputStream.close();
// get response
int responseCode = urlConnection.getResponseCode();
if(responseCode == 200) {
String response = readStream(urlConnection.getInputStream());
Gson gson = new Gson();
User user = gson.fromJson(response, User.class);
if(user.getUuid() != null) {
User.setCurrentUser(user);
Intent shoppingListIntent = new Intent(activity, ShoppingList.class);
activity.startActivity(shoppingListIntent);
} else {
RestResponseMessage rrm = gson.fromJson(response, RestResponseMessage.class);
writeToast(rrm.getMessage());
}
}
else
writeToast("Error while trying to complete login - wrong response");
}
catch (Exception e) {
Log.e("CONNECT ERROR GET USER", e.getClass().toString());
Log.e("CONNECT ERROR GET USER", e.getStackTrace().toString());
Log.e("CONNECT ERROR GET USER", e.getMessage());
writeToast("Error while trying to complete login");
}
finally {
if(urlConnection != null)
urlConnection.disconnect();
}
呈现的代码是在Runnable接口的run方法中实现Runnable接口的类中运行的代码的一部分。
这是调用类并在新线程中运行的方式:
GetUser getUser = new GetUser(u, activity);
Thread thr = new Thread(getUser);
thr.start();
最佳答案
问题一直在我的手机上。我启用了该功能,以便在发现更好的Wi-Fi信号时自动连接它们(启用了开发人员设置),这导致我的手机始终在两个网络之间切换,具体取决于我在房间/房屋中的位置。
同样,在切换网络时,需要再次运行应用程序,否则也会失败。
关于java - 使用urlConnection.getOutputStream()获取主机时出现问题;在我的真实设备上,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58858908/