Example #1
0
 public byte[] byteArrayHttpClient(final String urlString) throws Exception {
   OkHttpClient client = null;
   if (client == null) {
     client = new OkHttpClient();
     Cache responseCache = new Cache(CommonUtil.getImageSavePath(), 2 * 1024 * 1024);
     client.setCache(responseCache);
     client.setReadTimeout(30, java.util.concurrent.TimeUnit.SECONDS);
     client.setConnectTimeout(30, java.util.concurrent.TimeUnit.SECONDS);
   }
   FilterInputStream inputStream = getFromCache(urlString);
   if (inputStream != null) {
     return IOUtils.toByteArray(inputStream);
   }
   InputStream in = null;
   try {
     final String decodedUrl = URLDecoder.decode(urlString, "UTF-8");
     final URL url = new URL(decodedUrl);
     final Request request = new Request.Builder().url(url).build();
     final Response response = client.newCall(request).execute();
     in = response.body().byteStream();
     return IOUtils.toByteArray(in);
   } catch (final MalformedURLException e) {
   } catch (final OutOfMemoryError e) {
   } catch (final UnsupportedEncodingException e) {
   } catch (final IOException e) {
   } finally {
     if (in != null) {
       try {
         in.close();
       } catch (final IOException ignored) {
       }
     }
   }
   return null;
 }
Example #2
0
 private FilterInputStream getFromCache(String url) throws Exception {
   DiskLruCache cache = DiskLruCache.open(CommonUtil.getImageSavePath(), 1, 2, 2 * 1024 * 1024);
   cache.flush();
   String key = Util.hash(url);
   final DiskLruCache.Snapshot snapshot;
   try {
     snapshot = cache.get(key);
     if (snapshot == null) {
       return null;
     }
   } catch (IOException e) {
     return null;
   }
   FilterInputStream bodyIn =
       new FilterInputStream(snapshot.getInputStream(1)) {
         @Override
         public void close() throws IOException {
           snapshot.close();
           super.close();
         }
       };
   return bodyIn;
 }