2013년 5월 26일 일요일

HttpURLConnection에서 301, 302 오류 발생 시

Redirection Exception
java.net 패키지 내 HttpURLConnection 클래스를 이용하여 HTTP로 데이터를 받을 때 HTTP_OK (200)가 아닌 HTTP_MOVED_TEMP (302), HTTP_MOVED_PERM (301) 예외가 발생할 때가 있다. 두 가지 형태로 처리할 수 있을 거 같은데 하나는 Exception을 던져 더 이상 진행하지 못하게 하는 것이고 다른 하나는 Redirect된 URL을 새로 받아 처리하는 방식이다.
Redirected URL 수용하기
Redirect된 URL을 새로 받아 처리하려면 HttpURLConnection의 헤더에서 "Location" 정보를 받아 다시 Connect 한다.
public InputStream GetHTTPInputStream(URL url) throws Exception
{
    int redirectedCount = 0;
    while( redirectedCount <= 1 )    // Redirection 1번 허용
    {
        HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
            
        httpConn.setConnectTimeout(10000);    //< 연결 제한시간(단위 : msec, 0은 무한)
        httpConn.setReadTimeout(0);           //< 읽기 제한시간(단위 : msec, 0은 무한)
        httpConn.setUseCaches(false);         //< 캐시 사용 여부 설정(기본 설정: true)

        // URL을 요청하는 방법 설정 (GET|POST|HEAD|OPTIONS|PUT|DELETE|TRACE, 기본 설정: GET)
        httpConn.setRequestMethod("GET");
        
        int resCode = httpConn.getResponseCode();

        if( resCode == HttpsURLConnection.HTTP_OK )
        {
            return httpConn.getInputStream();
        }
        // Redirection 발생하는 경우
        else if( resCode == HttpsURLConnection.HTTP_MOVED_TEMP
              || resCode == HttpsURLConnection.HTTP_MOVED_PERM )
        {
            // Redirected URL 받아오기
            String redirectedUrl = httpConn.getHeaderField("Location");
            url = new URL(redirectedUrl);
        }
        // 이외의 오류는 Exception 처리
        else
            throw new MalformedURLException("can not connect to the url [" + url.toString() + "] Code: " + resCode);
        
        ++redirectedCount;
    }
}
저작자: Yes, 상업적 이용: No, 컨텐츠 변경: No

댓글 없음:

댓글 쓰기