OkHttpClient官网: http://square.github.io/okhttp/
OkHttp GitHub地址:https://github.com/square/okhttp
首先导入maven依赖:
<dependency> <groupId>com.squareup.okhttp3</groupId> <artifactId>okhttp</artifactId> <version>3.6.0</version> </dependency>
具体的代码实现:
public class OkHttpUtil { public static boolean downloadPic(OkHttpClient okHttpClient, String picUrl, String localFileName) { final File file = new File(localFileName); if (file.exists()) { file.delete(); } else { try { FileUtils.forceMkdir(file.getParentFile()); file.createNewFile(); } catch (IOException e) { log.error("create file failed, file = " + file.getAbsolutePath(), e); } } InputStream is = null; FileOutputStream fos = null; try { picUrl = FormatUtils.getItemPicUrl(picUrl); Request request = new Request.Builder().url(picUrl).build(); Call call = okHttpClient.newCall(request); Response response = call.execute(); byte[] buf = new byte[2048]; int len = 0; is = response.body().byteStream(); fos = new FileOutputStream(file); while ((len = is.read(buf)) != -1) { fos.write(buf, 0, len); } fos.flush(); return true; } catch (IOException e) { log.error("download failed", e); return false; } finally { try { if (is != null) { is.close(); } if (fos != null) { fos.close(); } } catch (IOException e) { log.error("down loaded failed", e); } } }(下篇将介绍将本地图片上传到阿里的OSS服务器中)