[java] HttpClient를 사용하여 웹 사이트에서 다운로드하는 동안 진행률을 표시하는 방법은?

Java에서 HttpClient를 사용하여 웹 사이트에서 파일을 다운로드하는 경우, 다운로드 진행률을 표시하는 것은 유용한 기능입니다. HttpClient 버전 4.x에서는 진행률 모니터링 기능을 제공하므로, 다음과 같이 코드를 작성하여 구현할 수 있습니다.

먼저, 필요한 클래스를 import합니다.

import org.apache.http.HttpEntity;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

다음으로, 다운로드 진행률을 표시하기 위해 다음과 같은 메서드를 작성합니다.

public void downloadFile(String url, String filePath) {
    HttpClient httpClient = new DefaultHttpClient();
    HttpGet httpGet = new HttpGet(url);
    
    try {
        HttpResponse response = httpClient.execute(httpGet);
        StatusLine statusLine = response.getStatusLine();
        int statusCode = statusLine.getStatusCode();
        
        if (statusCode == 200) {
            HttpEntity entity = response.getEntity();
            long fileSize = entity.getContentLength();
            
            InputStream inputStream = entity.getContent();
            FileOutputStream fileOutputStream = new FileOutputStream(filePath);
            
            byte[] buffer = new byte[1024];
            int bytesRead;
            long totalBytesRead = 0;
            
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                fileOutputStream.write(buffer, 0, bytesRead);
                totalBytesRead += bytesRead;
                
                // 다운로드 진행률 표시
                float progress = (float) totalBytesRead / fileSize * 100;
                System.out.printf("다운로드 진행률: %.2f%%\n", progress);
            }
            
            fileOutputStream.close();
            inputStream.close();
        } else {
            System.out.println("다운로드 실패: " + statusLine.getReasonPhrase());
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        httpClient.getConnectionManager().shutdown();
    }
}

위의 코드에서 downloadFile 메서드는 주어진 URL에서 파일을 다운로드하고, 진행률을 표시합니다. 파일을 저장할 경로는 filePath로 지정합니다.

다음은 downloadFile 메서드를 사용하는 예제 코드입니다.

public static void main(String[] args) {
    String url = "https://www.example.com/sample.pdf";
    String filePath = "C:\\downloads\\sample.pdf";
    
    DownloadProgressMonitor monitor = new DownloadProgressMonitor();
    monitor.downloadFile(url, filePath);
}

위의 예제에서는 url에 다운로드할 파일의 URL을, filePath에 저장할 파일의 경로를 지정합니다. 그런 다음 DownloadProgressMonitor 클래스의 인스턴스를 만들고, downloadFile 메서드를 호출합니다.

이제 웹 사이트에서 파일을 다운로드하는 동안 진행률을 표시하는 기능을 구현할 수 있습니다.