同样的是两个项目
1.下载文件
图片:
2.异步下载程序
package com.jun.web.okhttp;
import okhttp3.*;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
public class DownAsynFile {
public static void main(String[] args) {
downAsynFile();
}
private static void downAsynFile() {
OkHttpClient okHttpClient= new OkHttpClient();
String url = "http://localhost:8080/96.png";
Request request = new Request.Builder().url(url).build();
okHttpClient.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) {
InputStream inputStream = response.body().byteStream();
FileOutputStream fileOutputStream = null;
try {
fileOutputStream = new FileOutputStream(new File("E:/javafile/test/123.png"));
byte[] buffer = new byte[2048];
int len = 0;
while ((len = inputStream.read(buffer)) != -1) {
fileOutputStream.write(buffer, 0, len);
}
fileOutputStream.flush();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("===");
}
});
}
}