本文整理汇总了Java中com.squareup.okhttp.CacheControl类的典型用法代码示例。如果您正苦于以下问题:Java CacheControl类的具体用法?Java CacheControl怎么用?Java CacheControl使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
CacheControl类属于com.squareup.okhttp包,在下文中一共展示了CacheControl类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: fetch
import com.squareup.okhttp.CacheControl; //导入依赖的package包/类
@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);
}
}
示例2: computeFreshnessLifetime
import com.squareup.okhttp.CacheControl; //导入依赖的package包/类
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;
}
}
示例3: fetch
import com.squareup.okhttp.CacheControl; //导入依赖的package包/类
@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);
}
}
示例4: load
import com.squareup.okhttp.CacheControl; //导入依赖的package包/类
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);
}
}
示例5: startSynchronousGetRequest
import com.squareup.okhttp.CacheControl; //导入依赖的package包/类
@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;
}
}
开发者ID:MarcelBraghetto,项目名称:AndroidNanoDegreeProject3,代码行数:30,代码来源:DefaultNetworkRequestProvider.java
示例6: form
import com.squareup.okhttp.CacheControl; //导入依赖的package包/类
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;
}
示例7: isCacheable
import com.squareup.okhttp.CacheControl; //导入依赖的package包/类
/**
* 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;
}
示例8: createImageObservable
import com.squareup.okhttp.CacheControl; //导入依赖的package包/类
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);
}
}
});
}
示例9: isCacheable
import com.squareup.okhttp.CacheControl; //导入依赖的package包/类
/**
* 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;
}
示例10: generateRequest
import com.squareup.okhttp.CacheControl; //导入依赖的package包/类
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();
}
示例11: getCandidate
import com.squareup.okhttp.CacheControl; //导入依赖的package包/类
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);
}
示例12: requestPaymentRequest
import com.squareup.okhttp.CacheControl; //导入依赖的package包/类
@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());
}
}
});
}
示例13: send
import com.squareup.okhttp.CacheControl; //导入依赖的package包/类
@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());
}
}
});
}
示例14: makeRequest
import com.squareup.okhttp.CacheControl; //导入依赖的package包/类
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();
}
示例15: allowStaleCache
import com.squareup.okhttp.CacheControl; //导入依赖的package包/类
protected CacheControl allowStaleCache(int seconds) {
return new CacheControl.Builder().maxStale(seconds, TimeUnit.SECONDS).build();
}