1
我正在写一个接收服务器数据的Android应用程序。理论上可能没有互联网连接,所以我尝试通过捕获SocketTimeoutException来显示错误消息,重试屏幕或其他内容来捕获此案例。不幸的是,这个异常不会被抛出。至少它不会跳入catch子句。我究竟做错了什么?SocketTimeoutException等待但不被抛出?
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
}
}
谢谢,我混合了那些制定者:) – Bevor 2012-02-04 11:56:35