Example #1
0
 public static <T> T getCacheFile(InputBase input, Class<T> clazz) {
   Cache cache = requestQueue.getCache();
   Request<T> request =
       new GsonRequest<T>(input.method(), input.toString(), "", clazz, null, null, null, null);
   Cache.Entry entry = cache.get(request.getCacheKey());
   if (entry != null) {
     try {
       String json = new String(entry.data, "UTF-8");
       if (clazz == String.class) {
         return (T) json;
       }
       // File类型写文件后返回file对象
       else if (clazz == File.class) {
         String fileName = TextUtil.md5(input.toString());
         File outFile =
             new File(DirectoryManager.getDirectory(DirectoryManager.DIR.DATA), fileName);
         FileUtils.writeFile(outFile.getAbsolutePath(), entry.data);
         return (T) outFile;
       }
       // 替换服务端可能返回的错误的data格式
       json = json.replace("\"data\":[]", "\"data\":{}");
       // 服务器返回errNo=0
       if (json.matches(ERROR_NO_0_EXPRESSION)) {
         T data;
         JSONObject jsonObject = new JSONObject(json);
         json = jsonObject.getString("data");
         // 其他属于Gson请求,解析对象返回
         Gson gson = GsonUtil.createBuilder();
         data = (T) gson.fromJson(json, clazz);
         return data;
       }
       // 服务器返回errNo != 0
       else {
         return null;
       }
     } catch (Exception e) {
       return null;
     }
   }
   return null;
 }
Example #2
0
 public static <T> void removeCacheFile(InputBase input, Class<T> clazz) {
   Cache cache = requestQueue.getCache();
   Request<T> request =
       new GsonRequest<T>(input.method(), input.toString(), "", clazz, null, null, null, null);
   cache.remove(request.getCacheKey());
 }