2013-02-06 2 views
0

특히 호스트를 사용할 수없는 경우 HttpURLConnection에서 오류를 처리하기위한 최선의 방법을 찾고 있습니다. 내 소스?AsyncTask에서 HttpUrlConnection의 오류를 catch하십시오.

protected String doInBackground(String... strings) { 
    URL aURL; 
    String line; 
    HttpURLConnection connection; 
    BufferedReader reader; 
    StringBuilder stringBuilder = null; 
    try { 
     aURL = new URL(strings[0]); 
     connection = (HttpURLConnection) aURL.openConnection(); 


     InputStream aInputStream = connection.getInputStream(); 
     BufferedInputStream aBufferedInputStream = new BufferedInputStream(aInputStream); 

     reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); 
     stringBuilder = new StringBuilder(); 

     while ((line = reader.readLine()) != null) 
     { 
      stringBuilder.append(line); 
     } 

    } catch (IOException e) { 
     Log.d("svc", e.toString()); 
    } 
    return stringBuilder.toString(); 
} 
+0

글쎄, 예외가 잡혔습니다 - 당신은 * 어떤 일이 일어나기를 원합니 까? –

+0

처음에는'stringBuilder'를 할당하지 않았으므로 예외가 발생하면'return stringBuilder.toString();'에 문제가 있습니다. (NullPointerException, 나는 생각합니다) –

+0

안녕하세요, 결과를 반환하고 싶습니다. 좋아, 나는 return 문을 통해이 작업을 수행 할 수 있지만, 무엇이 더 중요합니까? 연결 (connection = (HttpURLConnection) aURL.openConnection();)에 의해 throw되는 예외를 catch하는 방법 또는 하나의 catch 블록 이 작업을 수행? – fillibuster

답변

1

을 변경해야 않았다 어떻게 connection.getResponseCode를 사용하여 다른 응답 코드()를 사용할 수 없습니다 당신이 설정됩니다 호스트에 대한 응답 코드에 대한 검사를 받게됩니다.

+0

그러나 서버를 사용할 수없는 경우 어떻게됩니까? (불안정한 네트워크). 이 경우 getResponseCode()의 결과는 무엇입니까? – fillibuster

+1

'HttpStatus.SC_OK' 이외의 것 –

+0

위대한, 고맙습니다 :-) – fillibuster

관련 문제