Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
OrganizationAdvent CalendarQiitadon (β)
Qiita JobsQiita ZineQiita Blog
Help us understand the problem. What is going on with this article?

[Java] ファイルをダウンロードして保存する(Apache HttpComponents HttpClient 4.5.2使用)

More than 3 years have passed since last update.


<!-- 省略 -->
<!-- 省略 -->
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

public class Main {
    public static void main(final String[] args) throws IOException {
        try (final CloseableHttpClient client = HttpClients.createDefault();
                final CloseableHttpResponse response = client.execute(new HttpGet("http://example.com/file"))) {
            final int status = response.getStatusLine().getStatusCode();
            if (status >= 200 && status < 300) {
                final HttpEntity entity = response.getEntity();
                Files.write(Paths.get("path/to/file"), entity == null ? new byte[0] : EntityUtils.toByteArray(entity));
            } else {
                throw new ClientProtocolException("Unexpected response status: " + status);


Apache HttpComponents - HttpComponents HttpClient Examples

Help us understand the problem. What is going on with this article?
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
SIerの下請けで詳細設計から単体試験までの工程を主に担当しています。業務経験のある言語はExcel VBAとパッケージソフト用のDSLだけです。


No comments
Sign up for free and join this conversation.
Sign Up
If you already have a Qiita account Login
Help us understand the problem. What is going on with this article?