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

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

Introduction

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

Prototype

HttpUrl url

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

Click Source Link

Usage

From source file:pct.droid.base.providers.media.HaruProvider.java

License:Open Source License

@Override
public Call getDetail(String videoId, final Callback callback) {
    Request.Builder requestBuilder = new Request.Builder();
    requestBuilder.url(API_URL + "anime.php?id=" + videoId);
    requestBuilder.tag(MEDIA_CALL);//w  w w.  j a va  2  s .  c o  m

    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);
                HaruResponse result = new HaruResponse(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 Haruhichan API"));
        }
    });
}

From source file:pct.droid.base.providers.media.YTSProvider.java

License:Open Source License

@Override
public Call getList(final ArrayList<Media> existingList, Filters filters, final Callback callback) {
    sFilters = filters;//from w w w .j a v a 2 s. c  om

    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;
    }

    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);
    requestBuilder.url(CURRENT_URL + "list_movies_pct.json?" + query);
    requestBuilder.tag(MEDIA_CALL);

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

From source file:pct.droid.base.providers.media.YTSProvider.java

License:Open Source License

@Override
public Call getDetail(String videoId, Callback callback) {
    Request.Builder requestBuilder = new Request.Builder();
    requestBuilder
            .url(API_URL + "list_movies_pct.json?query_term=" + videoId + "&limit=1&lang=" + sFilters.langCode);
    requestBuilder.addHeader("Host", "xor.image.yt");
    requestBuilder.tag(MEDIA_CALL);/*from  w w w  .  j  a  v  a2  s.com*/

    return fetchDetail(requestBuilder, callback);
}

From source file:pct.droid.base.providers.media.YTSProvider.java

License:Open Source License

private boolean generateFallback(Request.Builder requestBuilder) {
    String url = requestBuilder.build().urlString();
    if (url.contains(MIRROR_URL2)) {
        return false;
    } else if (url.contains(MIRROR_URL)) {
        url = url.replace(MIRROR_URL, MIRROR_URL2);
        CURRENT_URL = MIRROR_URL2;
    } else {//w w w.ja  v a 2 s . co  m
        url = url.replace(API_URL, MIRROR_URL);
        CURRENT_URL = MIRROR_URL;
    }
    requestBuilder.url(url);
    return true;
}

From source file:pct.droid.base.youtube.YouTubeData.java

License:Open Source License

/**
 * Calculate the YouTube URL to load the video.  Includes retrieving a token that YouTube
 * requires to play the video./*from  w  w  w  .j  a  v  a2 s.  c o m*/
 *
 * @param quality  quality of the video.  17=low, 18=high
 * @param fallback whether to fallback to lower quality in case the supplied quality is not available
 * @param videoId  the id of the video
 * @return the url string that will retrieve the video
 * @throws java.io.IOException
 */
public static String calculateYouTubeUrl(String quality, boolean fallback, String videoId) throws IOException {

    String uriStr = null;
    OkHttpClient client = PopcornApplication.getHttpClient();

    Request.Builder request = new Request.Builder();
    request.url(YOUTUBE_VIDEO_INFORMATION_URL + videoId);
    Call call = client.newCall(request.build());
    Response response = call.execute();

    String infoStr = response.body().string();

    String[] args = infoStr.split("&");
    Map<String, String> argMap = new HashMap<String, String>();
    for (String arg : args) {
        String[] valStrArr = arg.split("=");
        if (valStrArr.length >= 2) {
            argMap.put(valStrArr[0], URLDecoder.decode(valStrArr[1]));
        }
    }

    //Find out the URI string from the parameters

    //Populate the list of formats for the video
    String fmtList = URLDecoder.decode(argMap.get("fmt_list"), "utf-8");
    ArrayList<Format> formats = new ArrayList<Format>();
    if (null != fmtList) {
        String formatStrs[] = fmtList.split(",");

        for (String lFormatStr : formatStrs) {
            Format format = new Format(lFormatStr);
            formats.add(format);
        }
    }

    //Populate the list of streams for the video
    String streamList = argMap.get("url_encoded_fmt_stream_map");
    if (null != streamList) {
        String streamStrs[] = streamList.split(",");
        ArrayList<VideoStream> streams = new ArrayList<VideoStream>();
        for (String streamStr : streamStrs) {
            VideoStream lStream = new VideoStream(streamStr);
            streams.add(lStream);
        }

        //Search for the given format in the list of video formats
        // if it is there, select the corresponding stream
        // otherwise if fallback is requested, check for next lower format
        int formatId = Integer.parseInt(quality);

        Format searchFormat = new Format(formatId);
        while (!formats.contains(searchFormat) && fallback) {
            int oldId = searchFormat.getId();
            int newId = getSupportedFallbackId(oldId);

            if (oldId == newId) {
                break;
            }
            searchFormat = new Format(newId);
        }

        int index = formats.indexOf(searchFormat);
        if (index >= 0) {
            VideoStream searchStream = streams.get(index);
            uriStr = searchStream.getUrl();
        }

    }
    //Return the URI string. It may be null if the format (or a fallback format if enabled)
    // is not found in the list of formats for the video
    return uriStr;
}

From source file:twitter4j.AlternativeHttpClientImpl.java

License:Apache License

@Override
HttpResponse handleRequest(HttpRequest req) throws TwitterException {
    prepareOkHttpClient();//from w w w  .j a va2  s.c  o  m

    HttpResponse res = null;
    Request.Builder requestBuilder = new Request.Builder();
    requestBuilder.url(req.getURL()).headers(getHeaders(req));
    switch (req.getMethod()) {
    case HEAD:
    case DELETE:
    case PUT:
        break;
    case GET:
        requestBuilder.get();
        break;
    case POST:
        try {
            requestBuilder.post(getRequestBody(req));
        } catch (UnsupportedEncodingException e) {
            throw new TwitterException(e.getMessage(), e);
        }
        break;
    }
    final Request request = requestBuilder.build();

    int retriedCount;
    int retry = CONF.getHttpRetryCount() + 1;
    for (retriedCount = 0; retriedCount < retry; retriedCount++) {
        int responseCode = -1;
        try {
            Response response = okHttpClient.newCall(request).execute();
            lastRequestProtocol = response.header("OkHttp-Selected-Protocol");
            res = new OkHttpResponse(response, CONF);
            responseCode = response.code();

            if (logger.isDebugEnabled()) {
                logger.debug("Response: ");
                Map<String, List<String>> responseHeaders = res.getResponseHeaderFields();
                for (String key : responseHeaders.keySet()) {
                    List<String> values = responseHeaders.get(key);
                    for (String value : values) {
                        if (key != null) {
                            logger.debug(key + ": " + value);
                        } else {
                            logger.debug(value);
                        }
                    }
                }
            }
            if (responseCode < OK || (responseCode != FOUND && MULTIPLE_CHOICES <= responseCode)) {
                if (responseCode == ENHANCE_YOUR_CLAIM || responseCode == BAD_REQUEST
                        || responseCode < INTERNAL_SERVER_ERROR || retriedCount == CONF.getHttpRetryCount()) {

                    throw new TwitterException(res.asString(), res);
                }
            } else {
                break;
            }

        } catch (IOException e) {
            if (retriedCount == CONF.getHttpRetryCount()) {
                throw new TwitterException(e.getMessage(), e, responseCode);
            }
        }
        try {
            if (logger.isDebugEnabled() && res != null) {
                res.asString();
            }
            logger.debug("Sleeping " + CONF.getHttpRetryIntervalSeconds() + " seconds until the next retry.");
            Thread.sleep(CONF.getHttpRetryIntervalSeconds() * 1000);
        } catch (InterruptedException ignore) {
            //nothing to do
        }

    }
    return res;
}

From source file:windows.webservices.utilidades.EjecutorJson.java

private Request prepararRequest() {
    Request.Builder build;

    if ((json == null || json.isEmpty()) && metodosDeEnvio.equals(MetodosDeEnvio.POST) && param != null) {
        json = "recibir datos por query param";
    }// ww  w  .j a v  a 2  s .  com

    if (json != null && !json.equals("")) {
        build = new Request.Builder().url(uri.toString());
        RequestBody body = RequestBody.create(com.squareup.okhttp.MediaType.parse(MediaType.APPLICATION_JSON),
                json);
        build.addHeader(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON).addHeader(HttpHeaders.CONTENT_TYPE,
                MediaType.APPLICATION_JSON);
        switch (metodosDeEnvio) {
        case POST:
            prepararParam();
            build.url(uri.toString()).post(body);
            break;
        case GET:
            build.method(metodosDeEnvio.getMetodo(), body);
            break;
        case PUT:
            prepararParam();
            build.url(uri.toString()).put(body);
            break;
        case DELETE:
            prepararParam();
            build.url(uri.toString()).delete(body);
            break;
        }
    } else {
        prepararParam();
        build = new Request.Builder().url(uri.toString());
        build.method(metodosDeEnvio.getMetodo(), null);

    }
    return build.build();
}