okhttp 调用文件下载接口
时间: 2023-10-09 10:04:53 浏览: 71
你可以使用OkHttp库来调用文件下载接口。以下是使用OkHttp进行文件下载的示例代码:
```java
OkHttpClient client = new OkHttpClient();
String url = "http://your-file-url"; // 替换为实际的文件下载链接
Request request = new Request.Builder()
.url(url)
.build();
Call call = client.newCall(request);
Response response = call.execute();
if (response.isSuccessful()) {
ResponseBody body = response.body();
if (body != null) {
// 获取文件名
String fileName = response.header("Content-Disposition")
.replaceFirst("(?i)^.*filename=\"?([^\"]+)\"?.*$", "$1");
// 创建文件输出流
File file = new File("path-to-save-file/" + fileName);
FileOutputStream fos = new FileOutputStream(file);
// 读取并写入文件
InputStream inputStream = body.byteStream();
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
fos.write(buffer, 0, bytesRead);
}
// 关闭流
fos.flush();
fos.close();
inputStream.close();
System.out.println("文件下载成功");
}
} else {
System.out.println("文件下载失败");
}
```
请将上述代码中的 `"http://your-file-url"` 替换为实际的文件下载链接,`"path-to-save-file/"` 替换为你希望保存文件的路径。在代码执行完成后,如果文件下载成功,将会在指定的路径下保存文件,并打印"文件下载成功";否则,将打印"文件下载失败"。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)