[Java] URL을 통한 Binary 데이터 받기

자바에서 서버가 제공하는 바이너리 데이터를 받아 저장해 주는 코드입니다. 필요할 때 찾아 보기 쉽도록 정리해 봅니다.

URL url;
try {
    url = new URL("http://somewhere/binary.zip");
  
    URLConnection connection = url.openConnection();
    int contentLength = connection.getContentLength();
    if (contentLength > 0) {
        InputStream raw = connection.getInputStream();
        InputStream in = new BufferedInputStream(raw);
        byte[] data = new byte[contentLength];
        int bytesRead = 0;
        int offset = 0;
        while (offset < contentLength) {
            bytesRead = in.read(data, offset, data.length - offset);
            if (bytesRead == -1) break;
            offset += bytesRead;
        }
        in.close();
  
        if (offset == contentLength) {
            // 바이너리 데이터 준비 완료 !
            return true;
        }
    }
} catch (MalformedURLException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}

위의 코드는 사용해 보니 문제가 있습니다. 이유는 6번 코드를 통해 서버로부터 받은 데이터의 크기가 항상 옳바르지 않다는 것입니다. 예를 들어 데이터가 클 경우.. -1이 반환되기도 합니다. 이러한 이유로 위의 코드는 사용하면 않되고.. 아래의 코드를 사용하시기 바랍니다.

private boolean requestUrl(String urlString, ByteBuffer out) {
    URL url;
  
    try {
        url = new URL(urlString);
        URLConnection connection = url.openConnection();
        InputStream raw = connection.getInputStream();
        InputStream in = new BufferedInputStream(raw);
        byte[] chunk = new byte[1024];
        int bytesRead = 0;

        while((bytesRead = in.read(chunk)) != -1) {
            out.put (chunk, 0, bytesRead);
        }
   
        out.flip();
        in.close();
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }  
    
    return true;
}

크롬(Chrome)에서 플래시 디버거 기능 않될때 조치

크롬에서 플래시 빌더를 통해 개발을 할때 디버깅이 않되는 문제가 있습니다. 이에 대한 해결책입니다. 먼저 크롬을 실행하고 주소창에 about:plugins 을 입력하여 아래 창을 표시합니다.

사용자 삽입 이미지
Flash라고 되어 있는 부분에서 사용 중지를 클릭하여 해당 플러그인의 사용을 비활성화 시킨 후.. 다시 Flash PlugIn Debug를 다운받아 설치합니다. 요지는.. 개발자에게 잇어서 Flash는 2가지 버전이 있는데 하나는 Release용이고 하나는 Debug용입니다. 이중 Release는 사용하지 않고 오직 Debug용만 사용한다는 것입니다. 이렇게 하면 Flash Builder에서도 Chrome을 통해 디버깅이 가능해 집니다.