我正在编写一个从服务器接收数据的 Android 应用程序。理论上不可能有互联网连接,所以我尝试通过捕捉 SocketTimeoutException 来捕捉这种情况,以显示错误消息和重试屏幕或其他内容。不幸的是,不会抛出这个异常。至少它不会跳入 catch 子句。我究竟做错了什么?
public class HttpConnector {
private String urlString;
private int connectionTimeout = 5000; //milliseconds
public HttpConnector(String urlString) {
this.urlString = urlString;
}
public String receiveData() throws PolizeiwarnungException {
URL url = null;
HttpURLConnection urlConnection = null;
StringBuffer b = new StringBuffer();
try {
url = new URL(urlString);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setReadTimeout(connectionTimeout);
BufferedReader reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream())); //Here it gets stuck if there is no connection to the server
String str;
while ((str = reader.readLine()) != null) {
b.append(str + "\n");
}
}
catch (SocketTimeoutException e) {
//TODO
e.printStackTrace();
}
catch (IOException e) {
throw new PolizeiwarnungException(e);
}
finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
return b.toString();
}
public void sendData(String data) {
//TODO
}
}