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