使用CloseableHttpClient 用get请求去请求一个文件下载接口
时间: 2023-12-19 09:41:51 浏览: 246
可以使用 Apache 的 HttpClient 来实现。
以下是使用 CloseableHttpClient 发送 GET 请求并下载文件的示例代码:
```java
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
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.http.util.EntityUtils;
public class HttpClientExample {
public static void main(String[] args) throws Exception {
String url = "http://example.com/file/download?id=123";
String filePath = "/path/to/file"; // 文件保存路径
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpGet httpget = new HttpGet(url);
CloseableHttpResponse response = httpclient.execute(httpget);
try {
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream inputStream = entity.getContent();
FileOutputStream outputStream = new FileOutputStream(new File(filePath));
byte[] buffer = new byte[1024];
int len = -1;
while ((len = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, len);
}
outputStream.flush();
outputStream.close();
}
EntityUtils.consume(entity);
} finally {
response.close();
}
}
}
```
以上代码使用 CloseableHttpClient 发送 GET 请求,获取接口返回的文件流,并将文件保存到指定路径。你可以根据实际情况修改请求 URL、文件保存路径等参数。
阅读全文