httpclient下载
时间: 2023-09-02 19:08:26 浏览: 98
下面是使用 Apache HttpClient 进行文件下载的示例代码:
```java
import org.apache.http.HttpEntity;
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.commons.io.IOUtils;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class HttpClientDownloadExample {
public static void main(String[] args) {
String fileUrl = "http://example.com/file.pdf";
String savePath = "/path/to/save/file.pdf";
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
HttpGet httpGet = new HttpGet(fileUrl);
try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
HttpEntity entity = response.getEntity();
if (entity != null) {
try (InputStream inputStream = entity.getContent();
OutputStream outputStream = new FileOutputStream(savePath)) {
IOUtils.copy(inputStream, outputStream);
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
请将 `fileUrl` 设置为要下载的文件的 URL,将 `savePath` 设置为要保存文件的本地路径。以上代码使用 `HttpClients.createDefault()` 创建了一个默认的 `CloseableHttpClient` 实例,并发送了一个 HTTP GET 请求来下载文件。然后,使用 `IOUtils.copy()` 方法将文件内容从输入流复制到输出流,完成文件的下载和保存。
请注意,这只是一个基本示例,并且没有包含错误处理或其他高级功能。在实际使用中,您可能需要添加更多的逻辑以处理各种情况和异常。