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

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

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

More than 3 years have passed since last update.

割と基本的な処理なのにあんまりサンプルコード無いですね…。

pom.xml
<!-- 省略 -->
    <dependency>
      <groupId>org.apache.httpcomponents</groupId>
      <artifactId>httpclient</artifactId>
      <version>4.5.2</version>
    </dependency>
<!-- 省略 -->
Main.java
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

11
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
anqooqie
SIerの下請けで詳細設計から単体試験までの工程を主に担当しています。業務経験のある言語はExcel VBAとパッケージソフト用のDSLだけです。

Comments

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