Example usage for com.squareup.okhttp Response request

List of usage examples for com.squareup.okhttp Response request

Introduction

In this page you can find the example usage for com.squareup.okhttp Response request.

Prototype

Request request

To view the source code for com.squareup.okhttp Response request.

Click Source Link

Usage

From source file:at.bitfire.dav4android.BasicDigestAuthenticator.java

License:Open Source License

@Override
public Request authenticate(Proxy proxy, Response response) throws IOException {
    Request request = response.request();

    if (host != null && !request.httpUrl().host().equalsIgnoreCase(host)) {
        Constants.log.warn("Not authenticating against " + host + " for security reasons!");
        return null;
    }/*  www.ja v a  2 s  . co  m*/

    // check whether this is the first authentication try with our credentials
    Response priorResponse = response.priorResponse();
    boolean triedBefore = priorResponse != null ? priorResponse.request().header(HEADER_AUTHORIZATION) != null
            : false;

    HttpUtils.AuthScheme basicAuth = null, digestAuth = null;
    for (HttpUtils.AuthScheme scheme : HttpUtils
            .parseWwwAuthenticate(response.headers(HEADER_AUTHENTICATE).toArray(new String[0])))
        if ("Basic".equalsIgnoreCase(scheme.name))
            basicAuth = scheme;
        else if ("Digest".equalsIgnoreCase(scheme.name))
            digestAuth = scheme;

    // we MUST prefer Digest auth [https://tools.ietf.org/html/rfc2617#section-4.6]
    if (digestAuth != null) {
        // Digest auth

        if (triedBefore && !"true".equalsIgnoreCase(digestAuth.params.get("stale")))
            // credentials didn't work last time, and they won't work now -> stop here
            return null;
        return authorizationRequest(request, digestAuth);

    } else if (basicAuth != null) {
        // Basic auth
        if (triedBefore) // credentials didn't work last time, and they won't work now -> stop here
            return null;

        return request.newBuilder().header(HEADER_AUTHORIZATION, Credentials.basic(username, password)).build();
    }

    // no supported auth scheme
    return null;
}

From source file:at.bitfire.dav4android.exception.HttpException.java

License:Open Source License

public HttpException(Response response) {
    super(response.code() + " " + response.message());

    status = response.code();/*w  ww  . jav  a  2  s . com*/
    message = response.message();

    /* As we don't know the media type and character set of request and response body,
       only printable ASCII characters will be shown in clear text. Other octets will
       be shown as "[xx]" where xx is the hex value of the octet.
     */

    // format request
    Request request = response.request();
    StringBuilder formatted = new StringBuilder();
    formatted.append(request.method() + " " + request.urlString() + "\n");
    Headers headers = request.headers();
    for (String name : headers.names())
        for (String value : headers.values(name))
            formatted.append(name + ": " + value + "\n");
    if (request.body() != null)
        try {
            formatted.append("\n");
            Buffer buffer = new Buffer();
            request.body().writeTo(buffer);
            while (!buffer.exhausted())
                appendByte(formatted, buffer.readByte());
        } catch (IOException e) {
        }
    this.request = formatted.toString();

    // format response
    formatted = new StringBuilder();
    formatted.append(response.protocol() + " " + response.code() + " " + response.message() + "\n");
    headers = response.headers();
    for (String name : headers.names())
        for (String value : headers.values(name))
            formatted.append(name + ": " + value + "\n");
    if (response.body() != null)
        try {
            formatted.append("\n");
            for (byte b : response.body().bytes())
                appendByte(formatted, b);
        } catch (IOException e) {
        }
    this.response = formatted.toString();
}

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

License:Open Source License

/**
 * Fetch the list of movies from YTS/* ww  w .j  av  a 2s.  c  om*/
 *
 * @param currentList    Current shown list to be extended
 * @param requestBuilder Request to be executed
 * @param callback       Network callback
 * @return Call
 */
private Call fetchList(final ArrayList<Media> currentList, final Request.Builder requestBuilder,
        final Filters filters, final Callback callback) {
    return enqueue(requestBuilder.build(), new com.squareup.okhttp.Callback() {
        @Override
        public void onFailure(Request request, IOException e) {
            String url = requestBuilder.build().urlString();
            if (CURRENT_API >= API_URLS.length - 1) {
                callback.onFailure(e);
            } else {
                if (url.contains(API_URLS[CURRENT_API])) {
                    url = url.replace(API_URLS[CURRENT_API], API_URLS[CURRENT_API + 1]);
                    url = url.replace(API_URLS[CURRENT_API], API_URLS[CURRENT_API + 1]);
                    CURRENT_API++;
                } else {
                    url = url.replace(API_URLS[CURRENT_API - 1], API_URLS[CURRENT_API]);
                    url = url.replace(API_URLS[CURRENT_API - 1], API_URLS[CURRENT_API]);
                }
                requestBuilder.url(url);
                fetchList(currentList, requestBuilder, filters, callback);
            }
        }

        @Override
        public void onResponse(Response response) throws IOException {
            if (response.isSuccessful()) {
                String responseStr;
                try {
                    responseStr = response.body().string();
                } catch (SocketException e) {
                    onFailure(response.request(), new IOException("Socket failed"));
                    return;
                }

                VodoResponse result;
                try {
                    result = mGson.fromJson(responseStr, VodoResponse.class);
                } catch (IllegalStateException e) {
                    onFailure(response.request(), new IOException("JSON Failed"));
                    return;
                } catch (JsonSyntaxException e) {
                    onFailure(response.request(), new IOException("JSON Failed"));
                    return;
                }

                if (result == null) {
                    callback.onFailure(new NetworkErrorException("No response"));
                } else if (result.downloads == null || result.downloads.size() <= 0) {
                    callback.onFailure(new NetworkErrorException("No movies found"));
                } else {
                    ArrayList<Media> formattedData = result.formatForApp(currentList);
                    callback.onSuccess(filters, formattedData, true);
                    return;
                }
            }
            onFailure(response.request(), new IOException("Couldn't connect to Vodo"));
        }
    });
}

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

License:Open Source License

/**
 * @param context      Context//from  w ww  . j ava  2  s  . co  m
 * @param media        Media data
 * @param languageCode Code of language
 * @param callback     Network callback
 * @return Call
 */
public static Call download(final Context context, final Media media, final String languageCode,
        final com.squareup.okhttp.Callback callback) {
    OkHttpClient client = ButterApplication.getHttpClient();
    if (media.subtitles != null && media.subtitles.containsKey(languageCode)) {
        try {
            Request request = new Request.Builder().url(media.subtitles.get(languageCode)).build();
            Call call = client.newCall(request);

            final File subsDirectory = getStorageLocation(context);
            final String fileName = media.videoId + "-" + languageCode;
            final File srtPath = new File(subsDirectory, fileName + ".srt");

            if (srtPath.exists()) {
                callback.onResponse(null);
                return call;
            }

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

                @Override
                public void onResponse(Response response) throws IOException {
                    if (response.isSuccessful()) {
                        InputStream inputStream = null;
                        boolean failure = false;
                        try {

                            subsDirectory.mkdirs();
                            if (srtPath.exists()) {
                                File to = new File(subsDirectory, "temp" + System.currentTimeMillis());
                                srtPath.renameTo(to);
                                to.delete();
                            }

                            inputStream = response.body().byteStream();
                            String urlString = response.request().urlString();

                            if (urlString.contains(".zip") || urlString.contains(".gz")) {
                                SubsProvider.unpack(inputStream, srtPath, languageCode);
                            } else if (SubsProvider.isSubFormat(urlString)) {
                                parseFormatAndSave(urlString, srtPath, languageCode, inputStream);
                            } else {
                                callback.onFailure(response.request(),
                                        new IOException("FatalParsingException"));
                                failure = true;
                            }
                        } catch (FatalParsingException e) {
                            e.printStackTrace();
                            callback.onFailure(response.request(), new IOException("FatalParsingException"));
                            failure = true;
                        } catch (FileNotFoundException e) {
                            e.printStackTrace();
                            callback.onFailure(response.request(), e);
                            failure = true;
                        } catch (IOException e) {
                            e.printStackTrace();
                            callback.onFailure(response.request(), e);
                            failure = true;
                        } finally {
                            if (inputStream != null)
                                inputStream.close();

                            if (!failure)
                                callback.onResponse(response);
                        }
                    } else {
                        callback.onFailure(response.request(), new IOException("Unknown error"));
                    }
                }
            });

            return call;
        } catch (RuntimeException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    callback.onFailure(null, new IOException("Wrong media"));
    return null;
}

From source file:cn.com.canon.darwin.modules.service.api.interceptor.HttpLoggingInterceptor.java

License:Apache License

@Override
public Response intercept(Chain chain) throws IOException {
    Level level = this.level;

    Request request = chain.request();
    if (level == Level.NONE) {
        return chain.proceed(request);
    }//from ww  w  . j  a  v  a 2s.  co m

    boolean logBody = level == Level.BODY;
    boolean logHeaders = logBody || level == Level.HEADERS;

    RequestBody requestBody = request.body();
    boolean hasRequestBody = requestBody != null;

    Connection connection = chain.connection();

    Protocol protocol = connection != null ? connection.getProtocol() : Protocol.HTTP_1_1;
    String requestStartMessage = "--> " + request.method() + ' ' + request.url() + ' ' + protocol;
    if (!logHeaders && hasRequestBody) {
        requestStartMessage += " (" + requestBody.contentLength() + "-byte body)";
    }
    logger.log(requestStartMessage);

    if (logHeaders) {
        //            if (hasRequestBody) {
        //                // Request body headers are only present when installed as a
        //                // network interceptor. Force
        //                // them to be included (when available) so there values are
        //                // known.
        //                if (requestBody.contentType() != null) {
        //                    logger.log("Content-Type: " + requestBody.contentType());
        //                }
        //                if (requestBody.contentLength() != -1) {
        //                    logger.log("Content-Length: " + requestBody.contentLength());
        //                }
        //            }

        //            Headers headers = request.headers();
        //            for (int i = 0, count = headers.size(); i < count; i++) {
        //                String name = headers.name(i);
        //                // Skip headers from the request body as they are explicitly
        //                // logged above.
        //                if (!"Content-Type".equalsIgnoreCase(name) && !"Content-Length".equalsIgnoreCase(name)) {
        //                    logger.log(name + ": " + headers.value(i));
        //                }
        //            }

        if (!logBody || !hasRequestBody) {
            logger.log("--> END " + request.method());
        } else if (bodyEncoded(request.headers())) {
            logger.log("--> END " + request.method() + " (encoded body omitted)");
        } else {
            Buffer buffer = new Buffer();
            requestBody.writeTo(buffer);

            Charset charset = UTF8;
            MediaType contentType = requestBody.contentType();
            if (contentType != null) {
                charset = contentType.charset(UTF8);
            }

            logger.log("");
            if (isPlaintext(buffer)) {
                logger.log(buffer.readString(charset));
                logger.log("--> END " + request.method() + " (" + requestBody.contentLength() + "-byte body)");
            } else {
                logger.log("--> END " + request.method() + " (binary " + requestBody.contentLength()
                        + "-byte body omitted)");
            }
        }
    }

    long startNs = System.nanoTime();
    Response response;
    try {
        response = chain.proceed(request);
    } catch (Exception e) {
        logger.log("<-- HTTP FAILED: " + e);
        throw e;
    }
    long tookMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNs);

    ResponseBody responseBody = response.body();
    long contentLength = responseBody.contentLength();
    String bodySize = contentLength != -1 ? contentLength + "-byte" : "unknown-length";
    logger.log("<-- " + response.code() + ' ' + response.message() + ' ' + response.request().url() + " ("
            + tookMs + "ms" + (!logHeaders ? ", " + bodySize + " body" : "") + ')');

    //        if (logHeaders) {
    //            Headers headers = response.headers();
    //            for (int i = 0, count = headers.size(); i < count; i++) {
    //                logger.log(headers.name(i) + ": " + headers.value(i));
    //            }
    //
    if (!logBody || !HttpEngine.hasBody(response)) {
        logger.log("<-- END HTTP");
    } else if (bodyEncoded(response.headers())) {
        logger.log("<-- END HTTP (encoded body omitted)");
    } else {
        BufferedSource source = responseBody.source();
        source.request(Long.MAX_VALUE); // Buffer the entire body.
        Buffer buffer = source.buffer();

        Charset charset = UTF8;
        MediaType contentType = responseBody.contentType();
        if (contentType != null) {
            try {
                charset = contentType.charset(UTF8);
            } catch (UnsupportedCharsetException e) {
                logger.log("");
                logger.log("Couldn't decode the response body; charset is likely malformed.");
                logger.log("<-- END HTTP");

                return response;
            }
        }
        if (!isPlaintext(buffer)) {
            logger.log("");
            logger.log("<-- END HTTP (binary " + buffer.size() + "-byte body omitted)");
            return response;
        }
        if (contentLength != 0) {
            logger.log("");
            logger.log(buffer.clone().readString(charset));
        }
        logger.log("<-- END HTTP (" + buffer.size() + "-byte body)");
    }
    //        }

    return response;
}

From source file:cn.wochu.wh.net.OkHttpClientManager.java

License:Apache License

/**
 * // www .  ja  va2  s .c om
 *
 * @param url
 * @param destFileDir 
 * @param callback
 */
private void _downloadAsyn(final String url, final String destFileDir, final ResultCallback callback) {
    final Request request = new Request.Builder().url(url).build();
    final Call call = mOkHttpClient.newCall(request);
    call.enqueue(new Callback() {
        @Override
        public void onFailure(final Request request, final IOException e) {
            sendFailedStringCallback(request, e, callback);
        }

        @Override
        public void onResponse(Response response) {
            InputStream is = null;
            byte[] buf = new byte[2048];
            int len = 0;
            FileOutputStream fos = null;
            try {
                is = response.body().byteStream();
                File file = new File(destFileDir, getFileName(url));
                fos = new FileOutputStream(file);
                while ((len = is.read(buf)) != -1) {
                    fos.write(buf, 0, len);
                }
                fos.flush();
                //???
                sendSuccessResultCallback(file.getAbsolutePath(), callback);
            } catch (IOException e) {
                sendFailedStringCallback(response.request(), e, callback);
            } finally {
                try {
                    if (is != null)
                        is.close();
                } catch (IOException e) {
                }
                try {
                    if (fos != null)
                        fos.close();
                } catch (IOException e) {
                }
            }

        }
    });
}

From source file:cn.wochu.wh.net.OkHttpClientManager.java

License:Apache License

private void deliveryResult(final ResultCallback callback, Request request) {
    callback.onBefore(request);//from w w  w  . j a  v a2 s . c  om
    mOkHttpClient.newCall(request).enqueue(new Callback() {
        @Override
        public void onFailure(final Request request, final IOException e) {
            //sendFailedStringCallback(request, e, callback);
            callback.onError(request, e);
            callback.onAfter();
        }

        @Override
        public void onResponse(final Response response) {
            try {
                final String string = response.body().string();
                if (callback.mType == String.class) {
                    sendSuccessResultCallback(string, callback);
                } else {
                    Object o = mGson.fromJson(string, callback.mType);
                    sendSuccessResultCallback(o, callback);
                }

            } catch (IOException e) {
                sendFailedStringCallback(response.request(), e, callback);
            } catch (com.google.gson.JsonParseException e)//Json?
            {
                sendFailedStringCallback(response.request(), e, callback);
            }

        }
    });
}

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

License:Open Source License

@Test
public void networkInterceptorModifiedRequestIsReturned()
        throws IOException, InterruptedException, ExecutionException {
    server.enqueue(new MockResponse());

    Interceptor modifyHeaderInterceptor = new Interceptor() {
        @Override/*  w w w .  java 2s .co  m*/
        public Response intercept(Chain chain) throws IOException {
            return chain
                    .proceed(chain.request().newBuilder().header("User-Agent", "intercepted request").build());
        }
    };

    client.networkInterceptors().add(modifyHeaderInterceptor);

    Request request = new Request.Builder().url(server.getUrl("/")).header("User-Agent", "user request")
            .build();

    Response response = FiberOkHttpUtil.executeInFiber(client, request);
    assertNotNull(response.request().header("User-Agent"));
    assertEquals("user request", response.request().header("User-Agent"));
    assertEquals("intercepted request", response.networkResponse().request().header("User-Agent"));
}

From source file:co.paralleluniverse.fibers.okhttp.internal.RecordingOkAuthenticator.java

License:Open Source License

@Override
public Request authenticate(Proxy proxy, Response response) {
    responses.add(response);/*  w ww .j  a  v a  2s . c  o  m*/
    proxies.add(proxy);
    return response.request().newBuilder().addHeader("Authorization", credential).build();
}

From source file:co.paralleluniverse.fibers.okhttp.internal.RecordingOkAuthenticator.java

License:Open Source License

@Override
public Request authenticateProxy(Proxy proxy, Response response) {
    responses.add(response);// w w  w.j ava 2s  .c o  m
    proxies.add(proxy);
    return response.request().newBuilder().addHeader("Proxy-Authorization", credential).build();
}