Example usage for com.squareup.okhttp Call execute

List of usage examples for com.squareup.okhttp Call execute

Introduction

In this page you can find the example usage for com.squareup.okhttp Call execute.

Prototype

public Response execute() throws IOException 

Source Link

Document

Invokes the request immediately, and blocks until the response can be processed or is in error.

Usage

From source file:abtlibrary.utils.as24ApiClient.ApiClient.java

License:Apache License

/**
 * Execute HTTP call and deserialize the HTTP response body into the given return type.
 *
 * @param returnType The return type used to deserialize HTTP response body
 * @param <T> The return type corresponding to (same with) returnType
 * @param call Call/*from w  w  w  . j a  v a  2  s  .com*/
 * @return ApiResponse object containing response status, headers and
 *   data, which is a Java object deserialized from response body and would be null
 *   when returnType is null.
 * @throws ApiException If fail to execute the call
 */
public <T> ApiResponse<T> execute(Call call, Type returnType) throws ApiException {
    try {
        Response response = call.execute();
        T data = handleResponse(response, returnType);
        return new ApiResponse<T>(response.code(), response.headers().toMultimap(), data);
    } catch (IOException e) {
        throw new ApiException(e);
    }
}

From source file:butter.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.//  www. j av  a  2  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 = ButterApplication.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:cn.wochu.wh.net.OkHttpClientManager.java

License:Apache License

/**
 * ?Get// w  w  w  .  j  a v a  2s . c o  m
 *
 * @param url
 * @return Response
 */
private Response _getAsyn(String url) throws IOException {
    final Request request = new Request.Builder().url(url).build();
    Call call = mOkHttpClient.newCall(request);
    Response execute = call.execute();
    return execute;
}

From source file:co.aquario.socialkit.search.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./* w  ww.ja va 2 s. co  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 = "";
    OkHttpClient client = VMApp.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 listStory of formats for the video
    String fmtList = "";
    if (argMap.get("fmt_list") == null) {
        return "";
    } else {
        fmtList = URLDecoder.decode(argMap.get("fmt_list"), "utf-8");
    }

    ArrayList<co.aquario.socialkit.util.Format> formats = new ArrayList<co.aquario.socialkit.util.Format>();
    if (null != fmtList) {
        String formatStrs[] = fmtList.split(",");

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

    //Populate the listStory 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 listStory 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);

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

            if (oldId == newId) {
                break;
            }
            searchFormat = new co.aquario.socialkit.util.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 listStory of formats for the video
    return uriStr;
}

From source file:co.paralleluniverse.fibers.okhttp.CallTest.java

License:Open Source License

@Test
public void cancelWithInterceptor() throws Exception {
    client.interceptors().add(new Interceptor() {
        @Override/*from  w  ww  .  j av a2s .  c o  m*/
        public Response intercept(Chain chain) throws IOException {
            chain.proceed(chain.request());
            throw new AssertionError(); // We expect an exception.
        }
    });

    Call call = client.newCall(new Request.Builder().url(server.getUrl("/a")).build());
    call.cancel();

    try {
        call.execute();
        fail();
    } catch (IOException expected) {
    }
    assertEquals(0, server.getRequestCount());
}

From source file:co.paralleluniverse.fibers.okhttp.FiberOkHttpUtil.java

License:Open Source License

public static Response executeInFiber(final Call call) throws InterruptedException, IOException {
    return FiberUtil.runInFiberChecked(new SuspendableCallable<Response>() {
        @Override//from   w w  w .ja  va  2  s .  c  o  m
        public Response run() throws SuspendExecution, InterruptedException {
            try {
                return call.execute();
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        }
    }, IOException.class);
}

From source file:co.paralleluniverse.fibers.okhttp.FiberOkHttpUtils.java

License:Open Source License

public static Response executeSynchronously(final Call call)
        throws InterruptedException, IOException, ExecutionException {
    return fiberOkTry(new SuspendableCallable<Response>() {
        @Override/*from w  ww . ja va 2s  .c  om*/
        public Response run() throws SuspendExecution, InterruptedException {
            try {
                return call.execute();
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        }
    });
}

From source file:com.aix.city.comm.OkHttpStack.java

License:Open Source License

@Override
public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders)
        throws IOException, AuthFailureError {

    OkHttpClient client = mClient.clone();
    int timeoutMs = request.getTimeoutMs();
    client.setConnectTimeout(timeoutMs, TimeUnit.MILLISECONDS);
    client.setReadTimeout(timeoutMs, TimeUnit.MILLISECONDS);
    client.setWriteTimeout(timeoutMs, TimeUnit.MILLISECONDS);

    com.squareup.okhttp.Request.Builder okHttpRequestBuilder = new com.squareup.okhttp.Request.Builder();
    okHttpRequestBuilder.url(request.getUrl());

    Map<String, String> headers = request.getHeaders();
    for (final String name : headers.keySet()) {
        okHttpRequestBuilder.addHeader(name, headers.get(name));
    }//w ww. j ava 2  s  .co  m
    for (final String name : additionalHeaders.keySet()) {
        okHttpRequestBuilder.addHeader(name, additionalHeaders.get(name));
    }

    setConnectionParametersForRequest(okHttpRequestBuilder, request);

    com.squareup.okhttp.Request okHttpRequest = okHttpRequestBuilder.build();
    Call okHttpCall = client.newCall(okHttpRequest);
    Response okHttpResponse = okHttpCall.execute();

    StatusLine responseStatus = new BasicStatusLine(parseProtocol(okHttpResponse.protocol()),
            okHttpResponse.code(), okHttpResponse.message());
    BasicHttpResponse response = new BasicHttpResponse(responseStatus);
    response.setEntity(entityFromOkHttpResponse(okHttpResponse));

    Headers responseHeaders = okHttpResponse.headers();
    for (int i = 0, len = responseHeaders.size(); i < len; i++) {
        final String name = responseHeaders.name(i), value = responseHeaders.value(i);
        if (name != null) {
            response.addHeader(new BasicHeader(name, value));
        }
    }

    return response;
}

From source file:com.anony.okhttp.sample.CancelCall.java

License:Apache License

public void run() throws Exception {
    Request request = new Request.Builder().url("http://httpbin.org/delay/2") // This URL is served with a 2 second delay.
            .build();/*from  w  ww . j  a v  a2 s . co  m*/

    final long startNanos = System.nanoTime();
    final Call call = client.newCall(request);

    // Schedule a job to cancel the call in 1 second.
    executor.schedule(new Runnable() {
        @Override
        public void run() {
            System.out.printf("%.2f Canceling call.%n", (System.nanoTime() - startNanos) / 1e9f);
            call.cancel();
            System.out.printf("%.2f Canceled call.%n", (System.nanoTime() - startNanos) / 1e9f);
        }
    }, 1, TimeUnit.SECONDS);

    try {
        System.out.printf("%.2f Executing call.%n", (System.nanoTime() - startNanos) / 1e9f);
        Response response = call.execute();
        System.out.printf("%.2f Call was expected to fail, but completed: %s%n",
                (System.nanoTime() - startNanos) / 1e9f, response);
    } catch (IOException e) {
        System.out.printf("%.2f Call failed as expected: %s%n", (System.nanoTime() - startNanos) / 1e9f, e);
    }
}

From source file:com.capstone.transit.trans_it.TripPlannerActivity.java

License:Open Source License

private void getDirections(LatLng origin, LatLng destination) {

    final String directionsURL = getDirectionsUrl(origin, destination);
    Log.v(TAG, directionsURL);// www .  ja  v a 2  s . c o m

    if (isNetworkAvailable()) {

        Thread T = new Thread() {
            public void run() {
                OkHttpClient client = new OkHttpClient();
                Request request = new Request.Builder().url(directionsURL).build();

                Call call = client.newCall(request);
                try {
                    Response response = call.execute();
                    String jsonData = response.body().string();

                    Log.v(TAG, jsonData);

                    if (response.isSuccessful()) {

                        mStep = getSteps(jsonData);

                    } else {
                        alertUserAboutError();
                    }
                } catch (JSONException | IOException e) {
                    e.printStackTrace();
                }

            }
        };
        T.start();

        try {
            T.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    } else {
        Toast.makeText(this, "unavailable network", Toast.LENGTH_LONG).show();
    }
}