割と基本的な処理なのにあんまりサンプルコード無いですね…。
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);
}
}
}
}