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