@Override public void fetch(final OkHttpNetworkFetchState fetchState, final Callback callback) { fetchState.submitTime = SystemClock.uptimeMillis(); final Uri uri = fetchState.getUri(); try { Request request = new Request.Builder() .cacheControl(new CacheControl.Builder().noStore().build()) .url(uri.toString()) .get() .build(); fetchWithRequest(fetchState, callback, request); } catch (Exception e) { // handle error while creating the request callback.onFailure(e); } }
private long computeFreshnessLifetime() { CacheControl responseCaching = this.cacheResponse.cacheControl(); if (responseCaching.maxAgeSeconds() != -1) { return TimeUnit.SECONDS.toMillis((long) responseCaching.maxAgeSeconds()); } long delta; if (this.expires != null) { delta = this.expires.getTime() - (this.servedDate != null ? this.servedDate.getTime() : this.receivedResponseMillis); if (delta <= 0) { delta = 0; } return delta; } else if (this.lastModified == null || this.cacheResponse.request().httpUrl().query() != null) { return 0; } else { delta = (this.servedDate != null ? this.servedDate.getTime() : this .sentRequestMillis) - this.lastModified.getTime(); if (delta > 0) { return delta / 10; } return 0; } }
@Override public void fetch( final OkHttpNetworkFetchState fetchState, final NetworkFetcher.Callback callback) { fetchState.submitTime = SystemClock.uptimeMillis(); final Uri uri = fetchState.getUri(); try { Request request = new Request.Builder() .cacheControl(new CacheControl.Builder().noStore().build()) .url(uri.toString()) .get() .build(); fetchWithRequest(fetchState, callback, request); } catch (Exception e) { // handle error while creating the request callback.onFailure(e); } }
public Resources load(@Cache.Policy int policy) throws ExternalResourceException { buildUrl(); Logger.i(ExternalResources.TAG, "Load configuration from url: " + url.build()); final CacheControl cacheControl; switch (policy) { case Cache.POLICY_NONE: cacheControl = new CacheControl.Builder().noCache().noStore().build(); break; case Cache.POLICY_OFFLINE: cacheControl = CacheControl.FORCE_CACHE; break; case Cache.POLICY_ALL: default: cacheControl = new CacheControl.Builder().build(); break; } Logger.v(ExternalResources.TAG, "CachePolicy: " + policy); Request request = new Request.Builder().url(url.build()).cacheControl(cacheControl).build(); try { Response response = client.newCall(request).execute(); int responseCode = response.code(); Logger.d(ExternalResources.TAG, "Response code: " + responseCode); if (responseCode >= 300) { response.body().close(); throw new ResponseException(responseCode + " " + response.message(), policy, responseCode); } return converter.fromReader(response.body().charStream()); } catch (IOException e) { throw new ExternalResourceException(e); } }
@Nullable @Override public String startSynchronousGetRequest(@NonNull String url) { Request request = new Request.Builder() .url(url) .cacheControl(new CacheControl.Builder().maxAge(DEFAULT_CACHE_AGE_HOURS, TimeUnit.HOURS).build()) .addHeader(HEADER_ACCEPT_JSON_KEY, HEADER_ACCEPT_JSON_VALUE) .addHeader(HEADER_AUTH_TOKEN, mApiKey) .build(); try { Response response = mOkHttpClient.newCall(request).execute(); if(!response.isSuccessful()) { return null; } String responseBody = ""; if (response.body() != null) { responseBody = response.body().string(); response.body().close(); } return responseBody; } catch (IOException e) { return null; } }
private <ResultType extends ResultAdapter>ResultType form(METHOD method, Class<ResultType> resultType) throws WebException, IOException { Request.Builder reqestBuilder = new Request.Builder() .url(getFullUrl()) .cacheControl(new CacheControl.Builder().noCache().build()); addHeaderAll(reqestBuilder); FormEncodingBuilder body = new FormEncodingBuilder(); String[] keys = getParamKeys(); for (String key : keys) { body.add(key, param.get(key)); } Request request = initMethod(method, reqestBuilder, body.build()); String methodString = method.toString(); if(method.equals(METHOD.POST)){ methodString = method.toString()+"(FORM)"; } debugRequest(methodString, paramString); clearAllParams(); call = client.newCall(request); Response response = call.execute(); ResultType result = getResult(response, resultType); debugResponse(result.getBody(), response); unexpectedCode(response, result.getBody()); return result; }
/** * Returns true if {@code response} can be stored to later serve another * request. */ public static boolean isCacheable(Response response, Request request) { // Always go to network for uncacheable response codes (RFC 2616, 13.4), // This implementation doesn't support caching partial content. int responseCode = response.code(); if (responseCode != HttpURLConnection.HTTP_OK && responseCode != HttpURLConnection.HTTP_NOT_AUTHORITATIVE && responseCode != HttpURLConnection.HTTP_MULT_CHOICE && responseCode != HttpURLConnection.HTTP_MOVED_PERM && responseCode != HttpURLConnection.HTTP_GONE) { return false; } // Responses to authorized requests aren't cacheable unless they include // a 'public', 'must-revalidate' or 's-maxage' directive. CacheControl responseCaching = response.cacheControl(); if (request.header("Authorization") != null && !responseCaching.isPublic() && !responseCaching.mustRevalidate() && responseCaching.sMaxAgeSeconds() == -1) { return false; } if (responseCaching.noStore()) { return false; } return true; }
private Observable<Bitmap> createImageObservable(final String url, final ArtInfo artInfo) { return Observable.create(new Observable.OnSubscribe<Bitmap>() { @Override public void call(Subscriber<? super Bitmap> subscriber) { if (subscriber.isUnsubscribed()) { return; } InputStream is = null; try { //We don't want okhttp clogging its cache with these images CacheControl cc = new CacheControl.Builder().noStore().build(); Request req = new Request.Builder() .url(url).get().cacheControl(cc).build(); Response response = mOkHttpClient.newCall(req).execute(); if (response.isSuccessful()) { is = response.body().byteStream(); Bitmap bitmap = decodeBitmap(is, artInfo); if (bitmap != null && !subscriber.isUnsubscribed()) { subscriber.onNext(bitmap); subscriber.onCompleted(); return; } // else fall } // else fall if (!subscriber.isUnsubscribed()) { subscriber.onError(new Exception("unable to decode " + "bitmap for " + url)); } } catch (IOException | OutOfMemoryError e) { if (!subscriber.isUnsubscribed()) subscriber.onError(e); } finally { IOUtils.closeQuietly(is); } } }); }
/** * Returns true if this response can be stored to later serve another * request. */ public static boolean isCacheable(Response response, Request request) { // Always go to network for uncacheable response codes (RFC 2616, 13.4), // This implementation doesn't support caching partial content. int responseCode = response.code(); if (responseCode != HttpURLConnection.HTTP_OK && responseCode != HttpURLConnection.HTTP_NOT_AUTHORITATIVE && responseCode != HttpURLConnection.HTTP_MULT_CHOICE && responseCode != HttpURLConnection.HTTP_MOVED_PERM && responseCode != HttpURLConnection.HTTP_GONE) { return false; } // Responses to authorized requests aren't cacheable unless they include // a 'public', 'must-revalidate' or 's-maxage' directive. CacheControl responseCaching = response.cacheControl(); if (request.header("Authorization") != null && !responseCaching.isPublic() && !responseCaching.mustRevalidate() && responseCaching.sMaxAgeSeconds() == -1) { return false; } if (responseCaching.noStore()) { return false; } return true; }
public static Request generateRequest(String url, CacheType cacheType) { Request.Builder builder = new Request.Builder().url(url); if (cacheType == CacheType.USE_CACHE) { //Using cache, so the same call wont happen again for next 1 day. builder.cacheControl(new CacheControl.Builder() .maxStale(1, TimeUnit.DAYS) .build()); } return builder.build(); }
private CacheStrategy getCandidate() { if (this.cacheResponse == null) { return new CacheStrategy(this.request, null, null); } if (this.request.isHttps() && this.cacheResponse.handshake() == null) { return new CacheStrategy(this.request, null, null); } if (!CacheStrategy.isCacheable(this.cacheResponse, this.request)) { return new CacheStrategy(this.request, null, null); } CacheControl requestCaching = this.request.cacheControl(); if (requestCaching.noCache() || hasConditions(this.request)) { return new CacheStrategy(this.request, null, null); } long ageMillis = cacheResponseAge(); long freshMillis = computeFreshnessLifetime(); if (requestCaching.maxAgeSeconds() != -1) { freshMillis = Math.min(freshMillis, TimeUnit.SECONDS.toMillis((long) requestCaching .maxAgeSeconds())); } long minFreshMillis = 0; if (requestCaching.minFreshSeconds() != -1) { minFreshMillis = TimeUnit.SECONDS.toMillis((long) requestCaching.minFreshSeconds()); } long maxStaleMillis = 0; CacheControl responseCaching = this.cacheResponse.cacheControl(); if (!(responseCaching.mustRevalidate() || requestCaching.maxStaleSeconds() == -1)) { maxStaleMillis = TimeUnit.SECONDS.toMillis((long) requestCaching.maxStaleSeconds()); } if (responseCaching.noCache() || ageMillis + minFreshMillis >= freshMillis + maxStaleMillis) { Builder conditionalRequestBuilder = this.request.newBuilder(); if (this.etag != null) { conditionalRequestBuilder.header("If-None-Match", this.etag); } else if (this.lastModified != null) { conditionalRequestBuilder.header("If-Modified-Since", this.lastModifiedString); } else if (this.servedDate != null) { conditionalRequestBuilder.header("If-Modified-Since", this.servedDateString); } Request conditionalRequest = conditionalRequestBuilder.build(); if (hasConditions(conditionalRequest)) { return new CacheStrategy(conditionalRequest, this.cacheResponse, null); } return new CacheStrategy(conditionalRequest, null, null); } Response$Builder builder = this.cacheResponse.newBuilder(); if (ageMillis + minFreshMillis >= freshMillis) { builder.addHeader("Warning", "110 HttpURLConnection \"Response is stale\""); } if (ageMillis > a.h && isFreshnessLifetimeHeuristic()) { builder.addHeader("Warning", "113 HttpURLConnection \"Heuristic expiration\""); } return new CacheStrategy(null, builder.build(), null); }
@Override public void requestPaymentRequest(final String url) { super.backgroundHandler.post(new Runnable() { @Override public void run() { log.info("trying to request payment request from {}", url); final Request.Builder request = new Request.Builder(); request.url(url); request.cacheControl(new CacheControl.Builder().noCache().build()); request.header("Accept", PaymentProtocol.MIMETYPE_PAYMENTREQUEST); if (userAgent != null) request.header("User-Agent", userAgent); final Call call = Constants.HTTP_CLIENT.newCall(request.build()); try { final Response response = call.execute(); if (response.isSuccessful()) { final String contentType = response.header("Content-Type"); final InputStream is = response.body().byteStream(); new InputParser.StreamInputParser(contentType, is) { @Override protected void handlePaymentIntent(final PaymentIntent paymentIntent) { log.info("received {} via http", paymentIntent); onPaymentIntent(paymentIntent); } @Override protected void error(final int messageResId, final Object... messageArgs) { onFail(messageResId, messageArgs); } }.parse(); is.close(); } else { final int responseCode = response.code(); final String responseMessage = response.message(); log.info("got http error {}: {}", responseCode, responseMessage); onFail(R.string.error_http, responseCode, responseMessage); } } catch (final IOException x) { log.info("problem sending", x); onFail(R.string.error_io, x.getMessage()); } } }); }
@Override public void send(final Payment payment) { super.backgroundHandler.post(new Runnable() { @Override public void run() { log.info("trying to send tx to {}", url); final Request.Builder request = new Request.Builder(); request.url(url); request.cacheControl(new CacheControl.Builder().noCache().build()); request.header("Accept", PaymentProtocol.MIMETYPE_PAYMENTACK); if (userAgent != null) request.header("User-Agent", userAgent); request.post(new RequestBody() { @Override public MediaType contentType() { return MediaType.parse(PaymentProtocol.MIMETYPE_PAYMENT); } @Override public long contentLength() throws IOException { return payment.getSerializedSize(); } @Override public void writeTo(final BufferedSink sink) throws IOException { payment.writeTo(sink.outputStream()); } }); final Call call = Constants.HTTP_CLIENT.newCall(request.build()); try { final Response response = call.execute(); if (response.isSuccessful()) { log.info("tx sent via http"); final InputStream is = response.body().byteStream(); final Protos.PaymentACK paymentAck = Protos.PaymentACK.parseFrom(is); is.close(); final boolean ack = !"nack".equals(PaymentProtocol.parsePaymentAck(paymentAck).getMemo()); log.info("received {} via http", ack ? "ack" : "nack"); onResult(ack); } else { final int responseCode = response.code(); final String responseMessage = response.message(); log.info("got http error {}: {}", responseCode, responseMessage); onFail(R.string.error_http, responseCode, responseMessage); } } catch (final IOException x) { log.info("problem sending", x); onFail(R.string.error_io, x.getMessage()); } } }); }
private com.squareup.okhttp.Request makeRequest(Request request){ com.squareup.okhttp.Request.Builder rb = new com.squareup.okhttp.Request.Builder().url(request.getUrl()).tag(request.getTag()); Headers headers = createHeader(request.getHeaders()); if(headers!=null) rb.headers(headers); alexclin.httplite.RequestBody liteBody = request.getRequestBody(); RequestBody requestBody = null; if(liteBody!=null){ requestBody = mFactory.convertBody(liteBody,request.getWrapListener()); } switch (request.getMethod()){ case GET: rb = rb.get(); break; case POST: rb = rb.post(requestBody); break; case PUT: rb = rb.put(requestBody); break; case PATCH: rb = rb.patch(requestBody); break; case HEAD: rb = rb.head(); break; case DELETE: if(requestBody==null){ rb = rb.delete(); }else{ rb = rb.delete(requestBody); } break; } if(request.getCacheExpiredTime()>0){ rb.cacheControl(new CacheControl.Builder().maxAge(request.getCacheExpiredTime(), TimeUnit.SECONDS).build()); }else if(request.getCacheExpiredTime()== alexclin.httplite.Request.FORCE_CACHE){ rb.cacheControl(CacheControl.FORCE_CACHE); }else if(request.getCacheExpiredTime()== alexclin.httplite.Request.NO_CACHE){ rb.cacheControl(CacheControl.FORCE_NETWORK); } return rb.build(); }
protected CacheControl allowStaleCache(int seconds) { return new CacheControl.Builder().maxStale(seconds, TimeUnit.SECONDS).build(); }
/** Returns a strategy to use assuming the request can use the network. */ private CacheStrategy getCandidate() { // No cached response. if (cacheResponse == null) { return new CacheStrategy(request, null); } // Drop the cached response if it's missing a required handshake. if (request.isHttps() && cacheResponse.handshake() == null) { return new CacheStrategy(request, null); } // If this response shouldn't have been stored, it should never be used // as a response source. This check should be redundant as long as the // persistence store is well-behaved and the rules are constant. if (!isCacheable(cacheResponse, request)) { return new CacheStrategy(request, null); } CacheControl requestCaching = request.cacheControl(); if (requestCaching.noCache() || hasConditions(request)) { return new CacheStrategy(request, null); } long ageMillis = cacheResponseAge(); long freshMillis = computeFreshnessLifetime(); if (requestCaching.maxAgeSeconds() != -1) { freshMillis = Math.min(freshMillis, SECONDS.toMillis(requestCaching.maxAgeSeconds())); } long minFreshMillis = 0; if (requestCaching.minFreshSeconds() != -1) { minFreshMillis = SECONDS.toMillis(requestCaching.minFreshSeconds()); } long maxStaleMillis = 0; CacheControl responseCaching = cacheResponse.cacheControl(); if (!responseCaching.mustRevalidate() && requestCaching.maxStaleSeconds() != -1) { maxStaleMillis = SECONDS.toMillis(requestCaching.maxStaleSeconds()); } if (!responseCaching.noCache() && ageMillis + minFreshMillis < freshMillis + maxStaleMillis) { Response.Builder builder = cacheResponse.newBuilder(); if (ageMillis + minFreshMillis >= freshMillis) { builder.addHeader("Warning", "110 HttpURLConnection \"Response is stale\""); } long oneDayMillis = 24 * 60 * 60 * 1000L; if (ageMillis > oneDayMillis && isFreshnessLifetimeHeuristic()) { builder.addHeader("Warning", "113 HttpURLConnection \"Heuristic expiration\""); } return new CacheStrategy(null, builder.build()); } Request.Builder conditionalRequestBuilder = request.newBuilder(); if (lastModified != null) { conditionalRequestBuilder.header("If-Modified-Since", lastModifiedString); } else if (servedDate != null) { conditionalRequestBuilder.header("If-Modified-Since", servedDateString); } if (etag != null) { conditionalRequestBuilder.header("If-None-Match", etag); } Request conditionalRequest = conditionalRequestBuilder.build(); return hasConditions(conditionalRequest) ? new CacheStrategy(conditionalRequest, cacheResponse) : new CacheStrategy(conditionalRequest, null); }
/** Returns a strategy to use assuming the request can use the network. */ private CacheStrategy getCandidate() { // No cached response. if (cacheResponse == null) { return new CacheStrategy(request, null, ResponseSource.NETWORK); } // Drop the cached response if it's missing a required handshake. if (request.isHttps() && cacheResponse.handshake() == null) { return new CacheStrategy(request, null, ResponseSource.NETWORK); } // If this response shouldn't have been stored, it should never be used // as a response source. This check should be redundant as long as the // persistence store is well-behaved and the rules are constant. if (!isCacheable(cacheResponse, request)) { return new CacheStrategy(request, null, ResponseSource.NETWORK); } CacheControl requestCaching = request.cacheControl(); if (requestCaching.noCache() || hasConditions(request)) { return new CacheStrategy(request, cacheResponse, ResponseSource.NETWORK); } long ageMillis = cacheResponseAge(); long freshMillis = computeFreshnessLifetime(); if (requestCaching.maxAgeSeconds() != -1) { freshMillis = Math.min(freshMillis, SECONDS.toMillis(requestCaching.maxAgeSeconds())); } long minFreshMillis = 0; if (requestCaching.minFreshSeconds() != -1) { minFreshMillis = SECONDS.toMillis(requestCaching.minFreshSeconds()); } long maxStaleMillis = 0; CacheControl responseCaching = cacheResponse.cacheControl(); if (!responseCaching.mustRevalidate() && requestCaching.maxStaleSeconds() != -1) { maxStaleMillis = SECONDS.toMillis(requestCaching.maxStaleSeconds()); } if (!responseCaching.noCache() && ageMillis + minFreshMillis < freshMillis + maxStaleMillis) { Response.Builder builder = cacheResponse.newBuilder() .setResponseSource(ResponseSource.CACHE); // Overwrite any stored response source. if (ageMillis + minFreshMillis >= freshMillis) { builder.addHeader("Warning", "110 HttpURLConnection \"Response is stale\""); } long oneDayMillis = 24 * 60 * 60 * 1000L; if (ageMillis > oneDayMillis && isFreshnessLifetimeHeuristic()) { builder.addHeader("Warning", "113 HttpURLConnection \"Heuristic expiration\""); } return new CacheStrategy(null, builder.build(), ResponseSource.CACHE); } Request.Builder conditionalRequestBuilder = request.newBuilder(); if (lastModified != null) { conditionalRequestBuilder.header("If-Modified-Since", lastModifiedString); } else if (servedDate != null) { conditionalRequestBuilder.header("If-Modified-Since", servedDateString); } if (etag != null) { conditionalRequestBuilder.header("If-None-Match", etag); } Request conditionalRequest = conditionalRequestBuilder.build(); return hasConditions(conditionalRequest) ? new CacheStrategy(conditionalRequest, cacheResponse, ResponseSource.CONDITIONAL_CACHE) : new CacheStrategy(conditionalRequest, null, ResponseSource.NETWORK); }