Example usage for com.squareup.okhttp Response header

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

Introduction

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

Prototype

public String header(String name, String defaultValue) 

Source Link

Usage

From source file:com.digi.wva.internal.HttpClient.java

License:Mozilla Public License

/**
 * Log information of OkHttp Response objects
 *
 * <p>This method is protected, rather than private, due to a bug between JaCoCo and
 * the Android build tools which causes the instrumented bytecode to be invalid when this
 * method is private://from   www .  j a  va2s .  c o m
 * <a href="http://stackoverflow.com/questions/17603192/dalvik-transformation-using-wrong-invoke-opcode" target="_blank">see StackOverflow question.</a>
 * </p>
 * @param response the HTTP response object to log
 */
protected void logResponse(Response response) {
    if (!doLogging) {
        // Logging is disabled - do nothing.
        return;
    }

    Request request = response.request();

    StringBuilder log = new StringBuilder();
    log.append(
            // e.g. <-- 200 GET /ws/hw/leds/foo
            String.format("\u2190 %d %s %s", response.code(), request.method(), request.urlString()));

    // Add on lines tracking any redirects that occurred.
    Response prior = response.priorResponse();
    if (prior != null) {
        // Call out that there were prior responses.
        log.append(" (prior responses below)");

        // Add a line to the log message for each prior response.
        // (For most if not all responses, there will likely be just one.)
        do {
            log.append(String.format("\n... prior response: %d %s %s", prior.code(), prior.request().method(),
                    prior.request().urlString()));

            // If this is a redirect, log the URL we're being redirected to.
            if (prior.isRedirect()) {
                log.append(", redirecting to ");
                log.append(prior.header("Location", "[no Location header found?!]"));
            }

            prior = prior.priorResponse();
        } while (prior != null);
    }

    Log.i(TAG, log.toString());
}

From source file:com.liferay.mobile.screens.viewsets.defaultviews.webcontent.display.WebContentDisplayView.java

License:Open Source License

public WebViewClient getWebViewClientWithCustomHeader() {
    return new WebViewClient() {

        @Override//w w w.j a  v a 2s  .  co  m
        public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
            return getResource(url.trim());
        }

        @Override
        @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
        public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {

            return getResource(request.getUrl().toString());
        }

        private WebResourceResponse getResource(String url) {
            try {
                OkHttpClient httpClient = LiferayServerContext.getOkHttpClientNoCache();
                com.squareup.okhttp.Request.Builder builder = new com.squareup.okhttp.Request.Builder()
                        .url(url);

                Request request = builder.build();
                com.squareup.okhttp.Response response = httpClient.newCall(request).execute();

                return new WebResourceResponse(
                        response.header("content-type", response.body().contentType().type()),
                        response.header("content-encoding", "utf-8"), response.body().byteStream());
            } catch (Exception e) {
                return null;
            }
        }
    };
}

From source file:com.shahul3d.indiasatelliteweather.service.DownloaderService.java

License:Open Source License

@Background
public void downloadMap(int mapID) {
    //TODO: Check internet
    String mapType = appConstants.getMapType(mapID);
    String lastModifiedHeader = "";
    Log.d("Download requested for map type: " + mapType);
    updateDownloadStatus(mapID, 0);//from www. ja  v  a 2s  .  c om

    final String URL = appConstants.MAP_URL.get(mapType);

    try {
        Call call = httpClient.newCall(new Request.Builder().url(URL).get().build());
        Response response = call.execute();

        //TODO: These caching headers should be stored on preferences.
        String eTagHeader = response.header("ETag", "");
        lastModifiedHeader = response.header("Last-Modified", "");

        //            Log.d("eTagHeader: " + eTagHeader);
        Log.d("last modified: " + lastModifiedHeader);
        //            Log.d("\nN/W counts: " + httpClient.getCache().getNetworkCount() + "\nReq Counts: " + httpClient.getCache().getRequestCount() + "\nCache Hits: " + httpClient.getCache().getHitCount());

        if (response.code() == 200) {
            InputStream inputStream = null;
            ByteArrayOutputStream outArrrayIPStream = null;
            try {
                inputStream = response.body().byteStream();
                outArrrayIPStream = new ByteArrayOutputStream();
                byte[] buffer = new byte[1024];
                int statusUpdateTrigger = 0;
                long downloaded = 0;
                long responseSize = response.body().contentLength();

                Log.d("Total size: " + responseSize);

                for (int count; (count = inputStream.read(buffer)) != -1;) {
                    outArrrayIPStream.write(buffer, 0, count);
                    downloaded += count;
                    statusUpdateTrigger++;
                    //                        Log.d(String.format("%d / %d", downloaded, responseSize));

                    //Update download status
                    if (statusUpdateTrigger > appConstants.STATUS_UPDATE_THRESHOLD) {
                        //                            Thread.sleep(3000);
                        statusUpdateTrigger = 0;
                        Long downloadedPercent = downloaded * appConstants.MAX_DOWNLOAD_PROGRESS / responseSize;
                        Log.d("downloaded percent: " + downloadedPercent);
                        updateDownloadStatus(mapID, downloadedPercent.intValue());
                    }
                }

                byte[] responseImage = outArrrayIPStream.toByteArray();
                BitmapFactory.Options options = new BitmapFactory.Options();
                options.inMutable = true;
                Bitmap bmp = BitmapFactory.decodeByteArray(responseImage, 0, responseImage.length, options);

                bmp = removeMapBorders(mapType, bmp);

                //Save downloaded image for offline use.
                saveDownloadedMap(mapType, bmp);
                updateDownloadStatus(mapID, 100);
            } catch (IOException ignore) {
                trackException("MAP download & parser error", ignore);
                broadcastDownloadStatus(mapID, false);
                //Error on fetching & organizing the binary data.
                return;
            } finally {
                if (inputStream != null) {
                    inputStream.close();
                }
                if (outArrrayIPStream != null) {
                    outArrrayIPStream.close();
                }
            }
        } else {
            trackException("res code other than 200: " + response.code(), null);
            Log.d("res code other than 200 " + response.code());
            return;
        }
    } catch (IOException e) {
        trackException("MAP download connection error", e);
        broadcastDownloadStatus(mapID, false);
        return;
    }

    preferenceUtil.updateLastModifiedTime(preference_General, mapType, lastModifiedHeader);
    broadcastDownloadStatus(mapID, true);
}

From source file:com.yandex.disk.rest.RestClientIO.java

License:Apache License

long getUploadedSize(String url, Hash hash) throws IOException {

    Request request = buildRequest().removeHeader(Credentials.AUTHORIZATION_HEADER).url(url).head()
            .addHeader(ETAG_HEADER, hash.getMd5()).addHeader(SHA256_HEADER, hash.getSha256())
            .addHeader(SIZE_HEADER, String.valueOf(hash.getSize())).build();

    Response response = client.newCall(request).execute();

    int code = response.code();
    ResponseBody responseBody = response.body();
    responseBody.close();/*w  w w .  jav  a2 s .c  o  m*/
    switch (code) {
    case 200:
        return Long.valueOf(response.header(CONTENT_LENGTH_HEADER, "0"));
    default:
        return 0;
    }
}

From source file:io.macgyver.core.okhttp.LoggingInterceptor.java

License:Apache License

protected boolean isResponseBodySizeWithinLimit(Response response) {
    try {//w  ww. j a  va2 s.  c  o m
        if (Long.parseLong(response.header("Content-length", "0")) > maxPrintableBodySize) {
            return false;
        }
        return true;
    } catch (RuntimeException e) {
        slf4j.warn("problem reading content-length: " + e);
    }
    return false;
}