示例#1
0
 /**
  * 同步Get(一般不使用)
  *
  * @param url
  * @return String
  */
 public static String syncGet(String url) throws IOException {
   CacheControl cacheControl = CacheControl.FORCE_NETWORK;
   Request request = new Request.Builder().url(url).build();
   Response response = execute(request);
   if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
   Headers responseHeaders = response.headers();
   for (int i = 0; i < responseHeaders.size(); i++) {
     Log.i(TAG, responseHeaders.name(i) + ": " + responseHeaders.value(i));
   }
   Log.i(TAG, "cache response:    " + response.cacheResponse());
   Log.i(TAG, "network response:  " + response.networkResponse());
   return response.body().string();
 }
示例#2
0
  @Override
  public Response load(@NonNull Uri uri, int networkPolicy) throws IOException {
    CacheControl cacheControl = null;
    if (networkPolicy != 0) {
      if (NetworkPolicy.isTimeoutOnly(networkPolicy)) {
        cacheControl = TIMEOUT;
      } else if (NetworkPolicy.isOfflineOnly(networkPolicy)) {
        cacheControl = CacheControl.FORCE_CACHE;
      } else {
        CacheControl.Builder builder = new CacheControl.Builder();
        if (!NetworkPolicy.shouldReadFromDiskCache(networkPolicy)) {
          builder.noCache();
        }
        if (!NetworkPolicy.shouldWriteToDiskCache(networkPolicy)) {
          builder.noStore();
        }
        cacheControl = builder.build();
      }
    }

    Request.Builder builder = new Request.Builder().url(uri.toString());
    if (cacheControl != null) {
      builder.cacheControl(cacheControl);
    }

    com.squareup.okhttp.Response response = client.newCall(builder.build()).execute();
    int responseCode = response.code();
    if (responseCode >= 300) {
      response.body().close();
      throw new ResponseException(
          responseCode + " " + response.message(), networkPolicy, responseCode);
    }

    boolean fromCache = response.cacheResponse() != null;

    ResponseBody responseBody = response.body();
    return new Response(responseBody.byteStream(), fromCache, responseBody.contentLength());
  }
示例#3
0
 @Override
 public boolean fromDiskCache() {
   return mResponse.cacheResponse() != null;
 }