11
11

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

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

Last updated at Posted at 2016-05-18

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

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
11
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
11

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?