功能需求:将网络资源图片下载并存储至本地
1、添加依赖
OKhttp相比HttpURLConnection和httpClient更高效方便。项目采用gradle构建,首先添加OKhttp相关依赖,依赖如下(可查看jar包的最新版本:http://search.maven.org/ ):
dependencies {
compileOnly "***"
·
·
·
compile 'com.squareup.okhttp3:okhttp:3.4.1'
}
2、方法定义(以网络图片下载为例)
传参:
1、网络URL参数:photoOnlinePath;
2、本地存储路径:photoLocalPath
public void downloadPhoto(String photoOnlinePath, String photoLocalPath) {
File myPath = new File(photoLocalPath);
String directory = myPath.getParent();
File mydirectory = new File(directory);
if (!mydirectory.exists()) {
//若此目录不存在,则创建之
mydirectory.mkdirs();
}
OkHttpClient okHttpClient = new OkHttpClient();
okhttp3.Request request = new okhttp3.Request.Builder().get().url(photoOnlinePath).build();
try{
Response response = okHttpClient.newCall(request).execute();
if (!response.isSuccessful()) {
logger.debug("http request {} connect failed", photoOnlinePath);
} else {
logger.info("http request {} connect success,start write in", photoOnlinePath);
InputStream is;
is = response.body().byteStream();
FileOutputStream fos=null;
try{
fos = new FileOutputStream(myPath);
int len;
byte[] bytes = new byte[1024];
while ((len = is.read(bytes)) != -1) {
fos.write(bytes, 0, len);
}
}catch (IOException oue){
logger.debug("save photo {} to local dir {} failed!", photoOnlinePath, photoLocalPath);
}finally {
if (is != null) {
try{
is.close();
}catch (IOException isclose){
logger.error("close InputStream failed");
}
}
if (fos!=null){
try{
fos.close();
}catch (IOException fosclose){
logger.error("close FileOutputStream failed");
}
}
}
}
}catch (IOException e){
logger.error("http request {} connect failed", photoOnlinePath);
}
}