Example usage for com.squareup.okhttp Request.Builder tag

List of usage examples for com.squareup.okhttp Request.Builder tag

Introduction

In this page you can find the example usage for com.squareup.okhttp Request.Builder tag.

Prototype

Object tag

To view the source code for com.squareup.okhttp Request.Builder tag.

Click Source Link

Usage

From source file:butter.droid.base.providers.media.AnimeProvider.java

License:Open Source License

@Override
public Call getList(final ArrayList<Media> existingList, Filters filters, final Callback callback) {
    final ArrayList<Media> currentList;
    if (existingList == null) {
        currentList = new ArrayList<>();
    } else {//from  ww  w  .  j  ava 2  s .  c o m
        currentList = (ArrayList<Media>) existingList.clone();
    }

    ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new NameValuePair("limit", "30"));

    if (filters == null) {
        filters = new Filters();
    }

    if (filters.keywords != null) {
        params.add(new NameValuePair("keywords", filters.keywords));
    }

    if (filters.genre != null) {
        params.add(new NameValuePair("genre", filters.genre));
    }

    if (filters.order == Filters.Order.ASC) {
        params.add(new NameValuePair("order", "1"));
    } else {
        params.add(new NameValuePair("order", "-1"));
    }

    String sort;
    switch (filters.sort) {
    default:
    case POPULARITY:
        sort = "popularity";
        break;
    case YEAR:
        sort = "year";
        break;
    //            case DATE:
    //                sort = "updated";
    //                break;
    case RATING:
        sort = "rating";
        break;
    case ALPHABET:
        sort = "name";
        break;
    }

    params.add(new NameValuePair("sort", sort));

    String url = API_URLS[CURRENT_API] + "animes/";
    if (filters.page != null) {
        url += filters.page;
    } else {
        url += "1";
    }

    Request.Builder requestBuilder = new Request.Builder();
    String query = buildQuery(params);
    url = url + "?" + query;
    requestBuilder.url(url);
    requestBuilder.tag(MEDIA_CALL);

    Timber.d("AnimeProvider", "Making request to: " + url);

    return fetchList(currentList, requestBuilder, filters, callback);
}

From source file:butter.droid.base.providers.media.AnimeProvider.java

License:Open Source License

@Override
public Call getDetail(ArrayList<Media> currentList, Integer index, final Callback callback) {
    Request.Builder requestBuilder = new Request.Builder();
    String url = API_URLS[CURRENT_API] + "anime/" + currentList.get(index).videoId;
    requestBuilder.url(url);// ww  w  .j  a  v a 2 s  .  com
    requestBuilder.tag(MEDIA_CALL);

    Timber.d("AnimeProvider", "Making request to: " + url);

    return enqueue(requestBuilder.build(), new com.squareup.okhttp.Callback() {
        @Override
        public void onFailure(Request request, IOException e) {
            callback.onFailure(e);
        }

        @Override
        public void onResponse(Response response) throws IOException {
            if (response.isSuccessful()) {
                String responseStr = response.body().string();
                LinkedTreeMap<String, Object> map = mGson.fromJson(responseStr, LinkedTreeMap.class);
                AnimeResponse result = new AnimeResponse(map);
                if (map == null) {
                    callback.onFailure(new NetworkErrorException("Empty response"));
                } else {
                    ArrayList<Media> formattedData = result.formatDetailForPopcorn();

                    if (formattedData.size() > 0) {
                        callback.onSuccess(null, formattedData, true);
                        return;
                    }
                    callback.onFailure(new IllegalStateException("Empty list"));
                    return;
                }
            }
            callback.onFailure(new NetworkErrorException("Couldn't connect to AnimeAPI"));
        }
    });
}

From source file:butter.droid.base.providers.media.MoviesProvider.java

License:Open Source License

@Override
public Call getList(final ArrayList<Media> existingList, Filters filters, final Callback callback) {
    final ArrayList<Media> currentList;
    if (existingList == null) {
        currentList = new ArrayList<>();
    } else {//  w ww .  ja  v  a2  s  .c o  m
        currentList = (ArrayList<Media>) existingList.clone();
    }

    ArrayList<NameValuePair> params = new ArrayList<>();
    params.add(new NameValuePair("limit", "30"));

    if (filters == null) {
        filters = new Filters();
    }

    if (filters.keywords != null) {
        params.add(new NameValuePair("keywords", filters.keywords));
    }

    if (filters.genre != null) {
        params.add(new NameValuePair("genre", filters.genre));
    }

    if (filters.order == Filters.Order.ASC) {
        params.add(new NameValuePair("order", "1"));
    } else {
        params.add(new NameValuePair("order", "-1"));
    }

    if (filters.langCode != null) {
        params.add(new NameValuePair("lang", filters.langCode));
    }

    String sort;
    switch (filters.sort) {
    default:
    case POPULARITY:
        sort = "popularity";
        break;
    case YEAR:
        sort = "year";
        break;
    case DATE:
        sort = "last added";
        break;
    case RATING:
        sort = "rating";
        break;
    case ALPHABET:
        sort = "name";
        break;
    case TRENDING:
        sort = "trending";
        break;
    }

    params.add(new NameValuePair("sort", sort));

    String url = API_URLS[CURRENT_API] + "movies/";
    if (filters.page != null) {
        url += filters.page;
    } else {
        url += "1";
    }

    Request.Builder requestBuilder = new Request.Builder();
    String query = buildQuery(params);
    url = url + "?" + query;
    requestBuilder.url(url);
    requestBuilder.tag(MEDIA_CALL);

    Timber.d("MoviesProvider", "Making request to: " + url);

    return fetchList(currentList, requestBuilder, filters, callback);
}

From source file:butter.droid.base.providers.media.TVProvider.java

License:Open Source License

@Override
public Call getList(final ArrayList<Media> existingList, Filters filters, final Callback callback) {
    final ArrayList<Media> currentList;
    if (existingList == null) {
        currentList = new ArrayList<>();
    } else {//  ww  w.  j ava 2 s.  c  o m
        currentList = (ArrayList<Media>) existingList.clone();
    }

    ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new NameValuePair("limit", "30"));

    if (filters == null) {
        filters = new Filters();
    }

    if (filters.keywords != null) {
        params.add(new NameValuePair("keywords", filters.keywords));
    }

    if (filters.genre != null) {
        params.add(new NameValuePair("genre", filters.genre));
    }

    if (filters.order == Filters.Order.ASC) {
        params.add(new NameValuePair("order", "1"));
    } else {
        params.add(new NameValuePair("order", "-1"));
    }

    String sort = "";
    switch (filters.sort) {
    default:
    case POPULARITY:
        sort = "popularity";
        break;
    case TRENDING:
        sort = "trending";
        break;
    case YEAR:
        sort = "year";
        break;
    case DATE:
        sort = "updated";
        break;
    case RATING:
        sort = "rating";
        break;
    case ALPHABET:
        sort = "name";
        break;
    }

    params.add(new NameValuePair("sort", sort));

    String url = API_URLS[CURRENT_API] + "shows/";
    if (filters.page != null) {
        url += filters.page;
    } else {
        url += "1";
    }

    Request.Builder requestBuilder = new Request.Builder();
    String query = buildQuery(params);
    url = url + "?" + query;
    requestBuilder.url(url);
    requestBuilder.tag(MEDIA_CALL);

    Timber.d("TVProvider", "Making request to: " + url);

    return fetchList(currentList, requestBuilder, filters, callback);
}

From source file:butter.droid.base.providers.media.TVProvider.java

License:Open Source License

@Override
public Call getDetail(ArrayList<Media> currentList, Integer index, final Callback callback) {
    Request.Builder requestBuilder = new Request.Builder();
    String url = API_URLS[CURRENT_API] + "show/" + currentList.get(index).videoId;
    requestBuilder.url(url);/* w  ww  .  j  av  a  2 s.  co m*/
    requestBuilder.tag(MEDIA_CALL);

    Timber.d("TVProvider", "Making request to: " + url);

    return enqueue(requestBuilder.build(), new com.squareup.okhttp.Callback() {
        @Override
        public void onFailure(Request request, IOException e) {
            callback.onFailure(e);
        }

        @Override
        public void onResponse(Response response) throws IOException {
            if (response.isSuccessful()) {
                String responseStr = response.body().string();
                LinkedTreeMap<String, Object> map = mGson.fromJson(responseStr, LinkedTreeMap.class);
                TVReponse result = new TVReponse(map);
                if (map == null) {
                    callback.onFailure(new NetworkErrorException("Empty response"));
                } else {
                    ArrayList<Media> formattedData = result.formatDetailForPopcorn();

                    if (formattedData.size() > 0) {
                        callback.onSuccess(null, formattedData, true);
                        return;
                    }
                    callback.onFailure(new IllegalStateException("Empty list"));
                    return;
                }
            }
            callback.onFailure(new NetworkErrorException("Couldn't connect to TVAPI"));
        }
    });
}

From source file:butter.droid.base.providers.media.VodoProvider.java

License:Open Source License

@Override
public Call getList(final ArrayList<Media> existingList, Filters filters, final Callback callback) {
    sFilters = filters;/*  ww  w  .  ja va 2s. c  o m*/

    final ArrayList<Media> currentList;
    if (existingList == null) {
        currentList = new ArrayList<>();
    } else {
        currentList = (ArrayList<Media>) existingList.clone();
    }

    ArrayList<NameValuePair> params = new ArrayList<>();
    params.add(new NameValuePair("limit", "30"));

    if (filters == null) {
        filters = new Filters();
    }

    if (filters.keywords != null) {
        params.add(new NameValuePair("query_term", filters.keywords));
    }

    if (filters.genre != null) {
        params.add(new NameValuePair("genre", filters.genre));
    }

    if (filters.order == Filters.Order.ASC) {
        params.add(new NameValuePair("order_by", "asc"));
    } else {
        params.add(new NameValuePair("order_by", "desc"));
    }

    if (filters.langCode != null) {
        params.add(new NameValuePair("lang", filters.langCode));
    }

    String sort;
    switch (filters.sort) {
    default:
    case POPULARITY:
        sort = "seeds";
        break;
    case YEAR:
        sort = "year";
        break;
    case DATE:
        sort = "date_added";
        break;
    case RATING:
        sort = "rating";
        break;
    case ALPHABET:
        sort = "title";
        break;
    case TRENDING:
        sort = "trending_score";
        break;
    }

    params.add(new NameValuePair("sort_by", sort));

    if (filters.page != null) {
        params.add(new NameValuePair("page", Integer.toString(filters.page)));
    }

    Request.Builder requestBuilder = new Request.Builder();
    String query = "?" + buildQuery(params);
    // query not used, but still here as example
    requestBuilder.url(CURRENT_URL);
    requestBuilder.tag(MEDIA_CALL);

    return fetchList(currentList, requestBuilder, filters, callback);
}

From source file:butter.droid.base.providers.subs.YSubsProvider.java

License:Open Source License

@Override
public void getList(final Movie media, final Callback callback) {
    final Request.Builder requestBuilder = new Request.Builder();
    requestBuilder.url(API_URL + media.imdbId);
    requestBuilder.tag(SUBS_CALL);

    fetch(requestBuilder, media, new Callback() {
        @Override/*from   w w w.  j a v  a 2 s  .  co m*/
        public void onSuccess(Map<String, String> items) {
            callback.onSuccess(items);
        }

        @Override
        public void onFailure(Exception e) {
            requestBuilder.url(MIRROR_URL + media.imdbId);
            fetch(requestBuilder, media, callback);
        }
    });
}

From source file:com.facebook.react.modules.network.NetworkingModule.java

License:Open Source License

@ReactMethod
public void sendRequest(String method, String url, int requestId, ReadableArray headers, ReadableMap data,
        final Callback callback) {
    // We need to call the callback to avoid leaking memory on JS even when input for sending
    // request is erroneous or insufficient. For non-http based failures we use code 0, which is
    // interpreted as a transport error.
    // Callback accepts following arguments: responseCode, headersString, responseBody

    Request.Builder requestBuilder = new Request.Builder().url(url);

    if (requestId != 0) {
        requestBuilder.tag(requestId);
    }/*from www  . jav a  2s.  com*/

    Headers requestHeaders = extractHeaders(headers, data);
    if (requestHeaders == null) {
        callback.invoke(0, null, "Unrecognized headers format");
        return;
    }
    String contentType = requestHeaders.get(CONTENT_TYPE_HEADER_NAME);
    String contentEncoding = requestHeaders.get(CONTENT_ENCODING_HEADER_NAME);
    requestBuilder.headers(requestHeaders);

    if (data == null) {
        requestBuilder.method(method, null);
    } else if (data.hasKey(REQUEST_BODY_KEY_STRING)) {
        if (contentType == null) {
            callback.invoke(0, null, "Payload is set but no content-type header specified");
            return;
        }
        String body = data.getString(REQUEST_BODY_KEY_STRING);
        MediaType contentMediaType = MediaType.parse(contentType);
        if (RequestBodyUtil.isGzipEncoding(contentEncoding)) {
            RequestBody requestBody = RequestBodyUtil.createGzip(contentMediaType, body);
            if (requestBody == null) {
                callback.invoke(0, null, "Failed to gzip request body");
                return;
            }
            requestBuilder.method(method, requestBody);
        } else {
            requestBuilder.method(method, RequestBody.create(contentMediaType, body));
        }
    } else if (data.hasKey(REQUEST_BODY_KEY_URI)) {
        if (contentType == null) {
            callback.invoke(0, null, "Payload is set but no content-type header specified");
            return;
        }
        String uri = data.getString(REQUEST_BODY_KEY_URI);
        InputStream fileInputStream = RequestBodyUtil.getFileInputStream(getReactApplicationContext(), uri);
        if (fileInputStream == null) {
            callback.invoke(0, null, "Could not retrieve file for uri " + uri);
            return;
        }
        requestBuilder.method(method, RequestBodyUtil.create(MediaType.parse(contentType), fileInputStream));
    } else if (data.hasKey(REQUEST_BODY_KEY_FORMDATA)) {
        if (contentType == null) {
            contentType = "multipart/form-data";
        }
        ReadableArray parts = data.getArray(REQUEST_BODY_KEY_FORMDATA);
        MultipartBuilder multipartBuilder = constructMultipartBody(parts, contentType, callback);
        if (multipartBuilder == null) {
            return;
        }
        requestBuilder.method(method, multipartBuilder.build());
    } else {
        // Nothing in data payload, at least nothing we could understand anyway.
        // Ignore and treat it as if it were null.
        requestBuilder.method(method, null);
    }

    mClient.newCall(requestBuilder.build()).enqueue(new com.squareup.okhttp.Callback() {
        @Override
        public void onFailure(Request request, IOException e) {
            if (mShuttingDown) {
                return;
            }
            // We need to call the callback to avoid leaking memory on JS even when input for
            // sending request is erronous or insufficient. For non-http based failures we use
            // code 0, which is interpreted as a transport error
            callback.invoke(0, null, e.getMessage());
        }

        @Override
        public void onResponse(Response response) throws IOException {
            if (mShuttingDown) {
                return;
            }
            String responseBody;
            try {
                responseBody = response.body().string();
            } catch (IOException e) {
                // The stream has been cancelled or closed, nothing we can do
                callback.invoke(0, null, e.getMessage());
                return;
            }

            WritableMap responseHeaders = Arguments.createMap();
            Headers headers = response.headers();
            for (int i = 0; i < headers.size(); i++) {
                String headerName = headers.name(i);
                // multiple values for the same header
                if (responseHeaders.hasKey(headerName)) {
                    responseHeaders.putString(headerName,
                            responseHeaders.getString(headerName) + ", " + headers.value(i));
                } else {
                    responseHeaders.putString(headerName, headers.value(i));
                }
            }

            callback.invoke(response.code(), responseHeaders, responseBody);
        }
    });
}

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

License:Apache License

@Override
public void run() {
    isPending = false;//from  www.jav a  2  s  .  c o  m
    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:net.qiujuer.common.okhttp.core.HttpCore.java

License:Apache License

/**
 * ============Main call in this============
 *///from  ww w. j  a v a 2 s  .c  o m
protected Request.Builder setTag(Request.Builder builder, Object tag) {
    if (tag != null) {
        builder.tag(tag);
    }
    return builder;
}