Example usage for com.squareup.okhttp CacheControl FORCE_NETWORK

List of usage examples for com.squareup.okhttp CacheControl FORCE_NETWORK

Introduction

In this page you can find the example usage for com.squareup.okhttp CacheControl FORCE_NETWORK.

Prototype

CacheControl FORCE_NETWORK

To view the source code for com.squareup.okhttp CacheControl FORCE_NETWORK.

Click Source Link

Document

Cache control request directives that require network validation of responses.

Usage

From source file:com.liferay.mobile.screens.context.LiferayServerContext.java

License:Open Source License

public static OkHttpClient getOkHttpClientNoCache() {
    OkHttpClient noCacheClient = getOkHttpClient().clone();
    noCacheClient.interceptors().add(new Interceptor() {
        @Override/*from www .  j av  a  2 s  . c om*/
        public Response intercept(Chain chain) throws IOException {
            Request originalRequest = chain.request();

            Request newRequest = originalRequest.newBuilder().cacheControl(CacheControl.FORCE_NETWORK).build();

            return chain.proceed(newRequest);
        }
    });

    return noCacheClient;
}

From source file:com.liulishuo.filedownloader.services.FileDownloadRunnable.java

License:Apache License

@Override
public void run() {
    isPending = false;//from  ww w  .  j  a  v  a2s  . c om
    isRunning = true;
    int retryingTimes = 0;
    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);

    FileDownloadModel model = this.downloadModel;

    if (model == null) {
        FileDownloadLog.e(this, "start runnable but model == null?? %s", getId());

        this.downloadModel = helper.find(getId());

        if (this.downloadModel == null) {
            FileDownloadLog.e(this, "start runnable but downloadMode == null?? %s", getId());
            return;
        }

        model = this.downloadModel;
    }

    if (model.getStatus() != FileDownloadStatus.pending) {
        FileDownloadLog.e(this, "start runnable but status err %s", model.getStatus());
        // ??urlpath(????) ??
        onError(new RuntimeException(String.format("start runnable but status err %s", model.getStatus())));

        return;
    }

    // 
    do {

        long soFar = 0;
        try {

            if (model.isCanceled()) {
                FileDownloadLog.d(this, "already canceled %d %d", model.getId(), model.getStatus());
                break;
            }

            FileDownloadLog.d(FileDownloadRunnable.class, "start download %s %s", getId(), model.getUrl());

            checkIsContinueAvailable();

            Request.Builder headerBuilder = new Request.Builder().url(url);
            addHeader(headerBuilder);
            headerBuilder.tag(this.getId());
            // ?cache?REST?
            headerBuilder.cacheControl(CacheControl.FORCE_NETWORK);

            Call call = client.newCall(headerBuilder.get().build());

            Response response = call.execute();

            final boolean isSucceedStart = response.code() == 200;
            final boolean isSucceedContinue = response.code() == 206 && isContinueDownloadAvailable;

            if (isSucceedStart || isSucceedContinue) {
                long total = downloadTransfer.getTotalBytes();
                if (isSucceedStart || total == 0) {
                    total = response.body().contentLength();
                }

                if (isSucceedContinue) {
                    soFar = downloadTransfer.getSoFarBytes();
                    FileDownloadLog.d(this, "add range %d %d", downloadTransfer.getSoFarBytes(),
                            downloadTransfer.getTotalBytes());
                }

                InputStream inputStream = null;
                RandomAccessFile accessFile = getRandomAccessFile(isSucceedContinue);
                try {
                    inputStream = response.body().byteStream();
                    byte[] buff = new byte[BUFFER_SIZE];
                    maxNotifyBytes = maxNotifyCounts <= 0 ? -1 : total / maxNotifyCounts;

                    updateHeader(response);
                    onConnected(isSucceedContinue, soFar, total);

                    do {
                        int byteCount = inputStream.read(buff);
                        if (byteCount == -1) {
                            break;
                        }

                        accessFile.write(buff, 0, byteCount);

                        //write buff
                        soFar += byteCount;
                        if (accessFile.length() < soFar) {
                            // ??
                            throw new RuntimeException(
                                    String.format("file be changed by others when downloading %d %d",
                                            accessFile.length(), soFar));
                        } else {
                            onProcess(soFar, total);
                        }

                        if (isCancelled()) {
                            onPause();
                            return;
                        }

                    } while (true);

                    if (soFar == total) {
                        onComplete(total);

                        // ?
                        break;
                    } else {
                        throw new RuntimeException(
                                String.format("sofar[%d] not equal total[%d]", soFar, total));
                    }
                } finally {
                    if (inputStream != null) {
                        inputStream.close();
                    }

                    if (accessFile != null) {
                        accessFile.close();
                    }
                }

            } else {
                throw new RuntimeException(String.format("response code error: %d", response.code()));
            }

        } catch (Throwable ex) {
            // TODO ???????
            if (autoRetryTimes > retryingTimes++) {
                // retry
                onRetry(ex, retryingTimes, soFar);
                continue;
            } else {
                // error
                onError(ex);
                break;
            }
        } finally {
            isRunning = false;
        }

    } while (true);

}

From source file:org.quantumbadger.redreader.http.okhttp.OKHTTPBackend.java

License:Open Source License

@Override
public Request prepareRequest(final Context context, final RequestDetails details) {

    final com.squareup.okhttp.Request.Builder builder = new com.squareup.okhttp.Request.Builder();

    builder.header("User-Agent", Constants.ua(context));

    final List<PostField> postFields = details.getPostFields();

    if (postFields != null) {
        builder.post(RequestBody.create(MediaType.parse("application/x-www-form-urlencoded"),
                PostField.encodeList(postFields)));

    } else {//from  w  ww.  j av  a2 s. co  m
        builder.get();
    }

    builder.url(details.getUrl().toString());
    builder.cacheControl(CacheControl.FORCE_NETWORK);

    final AtomicReference<Call> callRef = new AtomicReference<>();

    return new Request() {

        public void executeInThisThread(final Listener listener) {

            final Call call = mClient.newCall(builder.build());
            callRef.set(call);

            try {

                final Response response;

                try {
                    response = call.execute();
                } catch (IOException e) {
                    listener.onError(CacheRequest.REQUEST_FAILURE_CONNECTION, e, null);
                    return;
                }

                final int status = response.code();

                if (status == 200 || status == 202) {

                    final ResponseBody body = response.body();
                    final InputStream bodyStream;
                    final Long bodyBytes;

                    if (body != null) {
                        bodyStream = body.byteStream();
                        bodyBytes = body.contentLength();

                    } else {
                        // TODO error
                        bodyStream = null;
                        bodyBytes = null;
                    }

                    final String contentType = response.header("Content-Type");

                    listener.onSuccess(contentType, bodyBytes, bodyStream);

                } else {
                    listener.onError(CacheRequest.REQUEST_FAILURE_REQUEST, null, status);
                }

            } catch (Throwable t) {
                listener.onError(CacheRequest.REQUEST_FAILURE_CONNECTION, t, null);
            }
        }

        @Override
        public void cancel() {
            final Call call = callRef.getAndSet(null);
            if (call != null) {
                call.cancel();
            }
        }

        @Override
        public void addHeader(final String name, final String value) {
            builder.addHeader(name, value);
        }
    };
}