HTTP요청 메서드에서 예외처리하기(url, json널값 처리)

주어진 url을 가지고 HTTP요청을 하고 응답을 받는 메서드,  makeHttpRequest가 있다.

이 메서드에서

  1. url이 널값이거나 
  2. 응답받는 JSON이 널이거나 빈 문자열일경우 

예외처리를 해주어야하는데, 이때 getResponseCode()를 사용해 응답코드가 200이 아닐경우 예외처리 한것을 코드로 살펴보자.



[예외처리 전]
/** * Make an HTTP request to the given URL and return a String as the response. */
private String makeHttpRequest(URL url) throws IOException {
    String jsonResponse = "";
    HttpURLConnection urlConnection = null;
    InputStream inputStream = null;
    try {
        urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setRequestMethod("GET");
        urlConnection.setReadTimeout(10000 /* milliseconds */);
        urlConnection.setConnectTimeout(15000 /* milliseconds */);
        urlConnection.connect();
        inputStream = urlConnection.getInputStream();
        jsonResponse = readFromStream(inputStream);
    } catch (IOException e) {
    } finally {
        if (urlConnection != null) {
            urlConnection.disconnect();
        }
        if (inputStream != null) {
            // function must handle java.io.IOException here
            inputStream.close();        }
    }
    return jsonResponse;
}

[예외처리 후]
private String makeHttpRequest(URL url) throws IOException {
    String jsonResponse = "";

    // if the url is null, we shouldn’t try to make the HTTP request.
    if (url == null){
        return jsonResponse;
    }

    HttpURLConnection urlConnection = null;
    InputStream inputStream = null;
    try {
        urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setRequestMethod("GET");
        urlConnection.setReadTimeout(10000 /* milliseconds */);
        urlConnection.setConnectTimeout(15000 /* milliseconds */);
        urlConnection.connect();

       if (urlConnection.getResponseCode() == 200){
           inputStream = urlConnection.getInputStream();
           jsonResponse = readFromStream(inputStream);
       }
    } catch (IOException e) {
    } finally {
        if (urlConnection != null) {
            urlConnection.disconnect();
        }
        if (inputStream != null) {
            // function must handle java.io.IOException here
            inputStream.close();
        }
    }
    return jsonResponse;
}

예외상황(1,2)에서 리턴값이 초기화값 그대로 출력되는것을 볼 수 있다.

댓글

이 블로그의 인기 게시물

API 요청 URL(URI) 만들기(조합하기) -Uri.Builder사용하기-

TextView에 글자를 넣어주는 방법(setText, append)

텍스트 뷰의 배경을 원형 이미지로 지정하고, 배경 색상 채우기(안드로이드)