package com.archser.accession.util;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
import java.util.Map.Entry;
import java.util.concurrent.TimeUnit;
import com.jfinal.kit.Kv;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class DownloadFileFromService {
private static DownloadFileFromService downloadUtil;
private final OkHttpClient okHttpClient;
public static final long DEFAULT_READ_TIMEOUT_MILLIS = 60 * 1000;
public static final long DEFAULT_WRITE_TIMEOUT_MILLIS = 60 * 1000;
public static final long DEFAULT_CONNECT_TIMEOUT_MILLIS = 60 * 1000;
public static DownloadFileFromService get() {
if (downloadUtil == null) {
downloadUtil = new DownloadFileFromService();
}
return downloadUtil;
}
public DownloadFileFromService() {
okHttpClient = new OkHttpClient();
okHttpClient.newBuilder()
.connectTimeout(DEFAULT_READ_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS)
.writeTimeout(DEFAULT_WRITE_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS)
.readTimeout(DEFAULT_WRITE_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS).build();
}
/**
* @param url 下载连接
* @param destFileDir 下载的文件储存目录
* @param destFileName 下载文件名称,后面记得拼接后缀,否则手机没法识别文件类型
* @param onDownloadListener
* @param listener 下载监听
*/
@SuppressWarnings("unchecked")
public boolean download(String url, Kv dataMap, String destFileDir, String destFileName, OnDownloadListener listener) {
boolean flag = false;
Iterator<Entry<String, String>> iterator = dataMap.entrySet().iterator();
StringBuffer buffer = new StringBuffer();
boolean isFirst = true;
while (iterator.hasNext()) {
Entry<String, String> next = iterator.next();
if (isFirst) {
buffer.append("?").append(next.getKey()).append("=").append(next.getValue());
isFirst = false;
} else {
buffer.append("&").append(next.getKey()).append("=").append(next.getValue());
}
}
Request request = new Request.Builder().addHeader("Accept-Encoding", "identity").url(url + buffer.toString()).build();
// 异步请求
okHttpClient.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
// TODO Auto-generated method stub
}
@Override
public void onResponse(Call call, Response response) throws IOException {
InputStream is = null;
byte[] buf = new byte[2048];
int len = 0;
FileOutputStream fos = null;
// 储存下载文件的目录
File dir = new File(destFileDir);
if (!dir.exists()) {
dir.mkdirs();
}
int progress = 0;
File file = new File(dir, destFileName);
try {
long sum = 0;
long total = response.body().contentLength();
is = response.body().byteStream();
fos = new FileOutputStream(file);
while ((len = is.read(buf)) != -1) {
fos.write(buf, 0, len);
sum += len;
progress = (int) (sum * 1.0f / total * 100);
listener.onDownloading(progress);
}
fos.flush();
listener.onDownloadSuccess(file);
} catch (Exception e) {
e.printStackTrace();
listener.onDownloadFailed(e);
} finally {
try {
if (is != null) {
is.close();
}
if (fos != null) {
fos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
});
return !flag;
}
/**
* 调用下载方式,监听下载进程
*@Time:2020年4月7日 - 下午8:35:58
* @auto:李德才
* @param: @param url
* @param: @param dataMap
* @param: @param dir
* @param: @param fileName
* @param: @return
* @return: boolean
* @throws
*/
public static boolean downFile(String url,Kv dataMap,String dir,String fileName) {
DownloadFileFromService.get().download(url, dataMap, dir,fileName,
new DownloadFileFromService.OnDownloadListener() {
@Override
public void onDownloadSuccess(File file) {
}
@Override
public void onDownloading(int progress) {
}
@Override
public void onDownloadFailed(Exception e) {
System.err.println("下载失败 ------->" + e.getMessage());
}
});
return false;
}
public interface OnDownloadListener{
/**
* 下载成功之后的文件
*/
void onDownloadSuccess(File file);
/**
* 下载进度
*/
void onDownloading(int progress);
/**
* 下载异常信息
*/
void onDownloadFailed(Exception e);
}
}
//调用
DownloadFileFromService.downFile();