package com.soft.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 com.jfinal.kit.Kv;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
/**
* 从服务器下载文件到本地
* 使用单例模式的OkHttp
* @author LDC
*
* 调用方式 DownloadFileFromService.get().download(...)
*/
public class DownloadFileFromService {
private static DownloadFileFromService downloadUtil;
private final OkHttpClient okHttpClient;
public static DownloadFileFromService get() {
if (downloadUtil == null) {
downloadUtil = new DownloadFileFromService();
}
return downloadUtil;
}
public DownloadFileFromService() {
okHttpClient = new OkHttpClient();
}
/**
* @param url 下载连接
* @param destFileDir 下载的文件储存目录
* @param destFileName 下载文件名称,后面记得拼接后缀,否则手机没法识别文件类型
* @param listener 下载监听
*/
@SuppressWarnings("unchecked")
public void download(String url, Kv dataMap, String destFileDir, String destFileName) {
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());
} else {
buffer.append(next.getKey()).append("=").append(next.getValue());
}
}
Request request = new Request.Builder().url(url + buffer.toString()).build();
OkHttpClient client = new OkHttpClient();
try {
client.newCall(request).execute();
} catch (IOException e) {
e.printStackTrace();
}
// 异步请求
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();
}
File file = new File(dir, destFileName);
try {
is = response.body().byteStream();
fos = new FileOutputStream(file);
while ((len = is.read(buf)) != -1) {
fos.write(buf, 0, len);
}
fos.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (is != null) {
is.close();
}
if (fos != null) {
fos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
});
}
}