Apache HttpClientを使ってファイルをダウンロード
Apache HttpClientを使用してファイルをダウンロードする手順:
- まず、Apache HttpClient の依存パッケージをインポートします。Maven を使用してプロジェクトの依存关系を管理している場合は、pom.xml ファイルに次の依存関係を追加できます。
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.13</version>
</dependency>
- HttpClient オブジェクトを作成する:
CloseableHttpClient httpClient = HttpClients.createDefault();
- HttpGetリクエストを作成し、リクエストのURLを設定します。
HttpGet httpGet = new HttpGet(url);
- リクエストを送信し、レスポンスを取得します。
CloseableHttpResponse response = httpClient.execute(httpGet);
- レスポンスのステータスコードを確認します。200であれば、リクエストは成功です。
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 200) {
// 文件下载逻辑
} else {
// 请求失败逻辑
}
- リクエストが成功していた場合、レスポンスからインプットストリームを取得し、インプットストリームをファイルに書き込みます。
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream inputStream = entity.getContent();
FileOutputStream outputStream = new FileOutputStream("output-file-path");
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.close();
inputStream.close();
}
- 最後に、HttpClient と HttpResponse オブジェクトを閉じるのを忘れないでください:
response.close();
httpClient.close();
こうすることで、Apache HttpClientを利用したファイルのダウンロード操作は完了します。