2012-02-04 2 views
1

서버에서 데이터를 수신하는 Android 앱을 작성 중입니다. 이론적으로는 인터넷 연결이 불가능하므로 SocketTimeoutException을 잡아서 재 시도 화면이나 다른 오류 메시지를 표시하여이 사례를 잡으려고합니다. 불행히도이 예외는 발생하지 않습니다. 적어도 그것은 catch 절에 뛰어 들지 않습니다. 내가 도대체 ​​뭘 잘못하고있는 겁니까?SocketTimeoutException 기다리고 있지만 throw되지 않았습니까?

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 
    } 
} 

답변

1

또한 연결 시간 제한을 설정해야합니다. Please see this documentation.

연결 지점이 없으므로 연결 시간 제한을 설정하지 않아도 연결 시간이 초과되지 않습니다. (INT 시간 제한)

setConnectTimeout는 이 URLConnection 인스턴스가 가리키는 리소스에 대한 연결을 설정 밀리 초 의 시간 제한 값을 설정합니다.

+0

감사합니다. – Bevor

관련 문제