如有不对的地方,望各路大神指点,小女子在此谢过O(∩_∩)O
点击此处下载demo,看完整代码,(*^__^*) 嘻嘻……
1.下载文件
/**
* 下载zip文件
*
* @param url
*/
private void downloadFile(final String url) {
OkHttpClient.Builder builder = new OkHttpClient.Builder().connectTimeout(20, TimeUnit.SECONDS)
.writeTimeout(5, TimeUnit.SECONDS)
.readTimeout(5, TimeUnit.SECONDS);
Request request = new Request.Builder().url(url).build();
builder.build().newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) throws IOException {
InputStream is = null;
byte[] buf = new byte[4096];
int len = 0;
FileOutputStream fos = null;
// 储存下载文件的目录
String savePath = Tools.isExistDir_html(filePath);
try {
is = response.body().byteStream();
long total = response.body().contentLength();
// File file = new File(savePath, getNameFromUrl(url));
File file = new File(savePath, getNameFromUrl(fileName));
fos = new FileOutputStream(file);
long sum = 0;
while ((len = is.read(buf)) != -1) {
fos.write(bu