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) 

Source Link

Usage

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

License:Open Source License

private static HttpEntity entityFromOkHttpResponse(Response r) throws IOException {
    BasicHttpEntity entity = new BasicHttpEntity();
    ResponseBody body = r.body();/*from  w  w w  . java 2 s. co m*/

    entity.setContent(body.byteStream());
    entity.setContentLength(body.contentLength());
    entity.setContentEncoding(r.header("Content-Encoding"));

    if (body.contentType() != null) {
        entity.setContentType(body.contentType().type());
    }
    return entity;
}

From source file:com.android.cloudfiles.cloudfilesforandroid.CloudFiles.java

License:Apache License

private String getBucketCdnUrl(String region, String bucket) throws IOException {

    Request request = new Request.Builder().url(cdnUrls.get(region) + "/" + bucket)
            .header("X-Auth-Token", getToken())

            .head().build();/*from w  w w .j ava2  s .com*/

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

    if (response.header("X-Cdn-Ssl-Uri") != null) {
        return response.header("X-Cdn-Ssl-Uri");
    } else {
        throw new IOException(bucket + " at region " + region + " not found");
    }

}

From source file:com.androidso.lib.net.http.OkHttpStack.java

License:Open Source License

private static HttpEntity entityFromOkHttpResponse(Response r) throws IOException {
    BasicHttpEntity entity = new BasicHttpEntity() {
        @Override//from w  w  w  . j a  v  a 2s. co  m
        public void consumeContent() {
            //                getContent().close();

        }
    };
    ResponseBody body = r.body();

    entity.setContent(body.byteStream());
    entity.setContentLength(body.contentLength());
    entity.setContentEncoding(r.header("Content-Encoding"));

    if (body.contentType() != null) {
        entity.setContentType(body.contentType().type());
    }
    return entity;
}

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

License:Apache License

public void run() throws Exception {
    Request request = new Request.Builder().url("https://api.github.com/repos/square/okhttp/issues")
            .header("User-Agent", "OkHttp Headers.java").addHeader("Accept", "application/json; q=0.5")
            .addHeader("Accept", "application/vnd.github.v3+json").build();

    Response response = client.newCall(request).execute();
    if (!response.isSuccessful())
        throw new IOException("Unexpected code " + response);

    System.out.println("Server: " + response.header("Server"));
    System.out.println("Date: " + response.header("Date"));
    System.out.println("Vary: " + response.headers("Vary"));
}

From source file:com.ayuget.redface.network.HTTPRedirection.java

License:Apache License

/**
 * Resolves a redirected URL {@code originalUrl} to its final location.
 *
 * If the URL is not really redirected, the original URL is returned.
 *///  ww w  . j a  v  a2 s. c o  m
public static Observable<String> resolve(final String originalUrl) {
    return Observable.create(new Observable.OnSubscribe<String>() {
        @Override
        public void call(Subscriber<? super String> subscriber) {
            OkHttpClient httpClient = new OkHttpClient();
            httpClient.setFollowRedirects(false);

            Request request = new Request.Builder().url(originalUrl).build();

            try {
                Response response = httpClient.newCall(request).execute();

                if (response.code() == REDIRECTED_STATUS_CODE) {
                    String locationHeader = response.header(LOCATION_HEADER);
                    String targetUrl = locationHeader == null ? originalUrl
                            : "http://" + new URL(originalUrl).getHost() + locationHeader;
                    Timber.d("URL '%s' is redirected to '%s'", originalUrl, targetUrl);
                    subscriber.onNext(targetUrl);
                } else {
                    Timber.w("URL '%s' is not redirected", originalUrl);
                    subscriber.onNext(originalUrl);
                }
            } catch (IOException e) {
                subscriber.onError(e);
            }
        }
    });
}

From source file:com.commonsware.android.backup.BackupService.java

License:Apache License

private void uploadBackup(File backup) throws IOException {
    Request request = new Request.Builder().url(URL_CREATE_BACKUP).post(RequestBody.create(JSON, "{}")).build();
    Response response = OKHTTP_CLIENT.newCall(request).execute();

    if (response.code() == 201) {
        String backupURL = response.header("Location");

        request = new Request.Builder().url(backupURL + RESOURCE_DATASET).put(RequestBody.create(ZIP, backup))
                .build();/*from w  ww  . java 2 s  .  com*/
        response = OKHTTP_CLIENT.newCall(request).execute();

        if (response.code() == 201) {
            String datasetURL = response.header("Location");
            SharedPreferences prefs = getSharedPreferences(getClass().getName(), Context.MODE_PRIVATE);

            prefs.edit().putString(PREF_LAST_BACKUP_DATASET, datasetURL).commit();
        } else {
            Log.e(getClass().getSimpleName(), "Unsuccessful request to upload backup");
        }
    } else {
        Log.e(getClass().getSimpleName(), "Unsuccessful request to create backup");
    }
}

From source file:com.datastore_android_sdk.okhttp.OkHttpStack.java

License:Open Source License

private URLHttpResponse responseFromConnection(Response okHttpResponse) throws IOException {
    URLHttpResponse response = new URLHttpResponse();
    //contentStream
    int responseCode = okHttpResponse.code();
    if (responseCode == -1) {
        throw new IOException("Could not retrieve response code from HttpUrlConnection.");
    }//from w w w  . j a  v  a 2s.  com
    response.setResponseCode(responseCode);
    response.setResponseMessage(okHttpResponse.message());

    response.setContentStream(okHttpResponse.body().byteStream());

    response.setContentLength(okHttpResponse.body().contentLength());
    response.setContentEncoding(okHttpResponse.header("Content-Encoding"));
    if (okHttpResponse.body().contentType() != null) {
        response.setContentType(okHttpResponse.body().contentType().type());
    }

    //header
    HashMap<String, String> headerMap = new HashMap<>();
    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) {
            headerMap.put(name, value);
        }
    }
    response.setHeaders(headerMap);
    return response;
}

From source file:com.facebook.stetho.okhttp.StethoInterceptor.java

License:Open Source License

@Override
public Response intercept(Chain chain) throws IOException {
    String requestId = mEventReporter.nextRequestId();

    Request request = chain.request();

    RequestBodyHelper requestBodyHelper = null;
    if (mEventReporter.isEnabled()) {
        requestBodyHelper = new RequestBodyHelper(mEventReporter, requestId);
        OkHttpInspectorRequest inspectorRequest = new OkHttpInspectorRequest(requestId, request,
                requestBodyHelper);/*from   w w w.  ja v  a 2s. c o  m*/
        mEventReporter.requestWillBeSent(inspectorRequest);
    }

    Response response;
    try {
        response = chain.proceed(request);
    } catch (IOException e) {
        if (mEventReporter.isEnabled()) {
            mEventReporter.httpExchangeFailed(requestId, e.toString());
        }
        throw e;
    }

    if (mEventReporter.isEnabled()) {
        if (requestBodyHelper != null && requestBodyHelper.hasBody()) {
            requestBodyHelper.reportDataSent();
        }

        Connection connection = chain.connection();
        mEventReporter
                .responseHeadersReceived(new OkHttpInspectorResponse(requestId, request, response, connection));

        ResponseBody body = response.body();
        MediaType contentType = null;
        InputStream responseStream = null;
        if (body != null) {
            contentType = body.contentType();
            responseStream = body.byteStream();
        }

        responseStream = mEventReporter.interpretResponseStream(requestId,
                contentType != null ? contentType.toString() : null, response.header("Content-Encoding"),
                responseStream, new DefaultResponseHandler(mEventReporter, requestId));
        if (responseStream != null) {
            response = response.newBuilder().body(new ForwardingResponseBody(body, responseStream)).build();
        }
    }

    return response;
}

From source file:com.github.airk.tool.sobitmap.NetworkHunter.java

License:Apache License

@Override
File preCacheFile() {/* w w  w . ja v  a  2s .  co m*/
    File file = null;
    try {
        Request netReq = new Request.Builder().url(request.source.toString()).build();
        Response response = client.newCall(netReq).execute();
        if (response.code() >= 300) {
            if (SoBitmap.LOG) {
                Log.d(SoBitmap.TAG, tag() + ": Network error occurred..." + response.code());
            }
            response.body().close();
            request.e = new HuntException(HuntException.REASON_NETWORK_ERROR);
            request.e.setExtra(response.code() + "");
            return null;
        }
        if (SoBitmap.LOG) {
            Log.d(SoBitmap.TAG, tag() + ": Downloading...");
        }
        String size = response.header("content-length");
        if (size != null && !request.options.onlyLevel && Long.parseLong(size) > request.options.maxInput) {
            request.e = new HuntException(HuntException.REASON_TOO_LARGE);
            return null;
        }
        file = new File(request.cacheDir, request.tag);
        Util.inputStreamToFile(file, response.body().byteStream());
        if (SoBitmap.LOG) {
            Log.d(SoBitmap.TAG, tag() + ": Downloaded to file -> " + file.getAbsolutePath());
        }
        if (!file.exists()) { //UNLIKELY
            request.e = new HuntException(HuntException.REASON_FILE_NOT_FOUND);
            request.e.setExtra("Download success but file not found.");
            return null;
        } else {
            if (!request.options.onlyLevel && file.length() / 1024 > request.options.maxInput) {
                request.e = new HuntException(HuntException.REASON_TOO_LARGE);
                return null;
            }
        }
    } catch (SocketException e) {
        e.printStackTrace();
        request.e = new HuntException(HuntException.REASON_NETWORK_ERROR);
    } catch (IOException ignore) {
        request.e = new HuntException(HuntException.REASON_IO_EXCEPTION);
    }
    return file;
}

From source file:com.gzsll.downloads.DownloadThread.java

License:Apache License

/**
 * Read headers from the HTTP response and store them into local state.
 */// www  .j ava  2s.c  o  m
private void readResponseHeaders(State state, InnerState innerState, Response response) throws StopRequest {
    String header = response.header("Content-Disposition");
    if (header != null) {
        innerState.mHeaderContentDisposition = header;
    }
    header = response.header("Content-Location");
    if (header != null) {
        innerState.mHeaderContentLocation = header;
    }
    if (state.mMimeType == null) {
        header = response.header("Content-Type");
        if (header != null) {
            state.mMimeType = sanitizeMimeType(header);
        }
    }
    header = response.header("ETag");
    if (header != null) {
        innerState.mHeaderETag = header;
    }
    String headerTransferEncoding = null;
    header = response.header("Transfer-Encoding");
    if (header != null) {
        headerTransferEncoding = header;
    }
    if (headerTransferEncoding == null) {
        header = response.header("Content-Length");
        if (header != null) {
            innerState.mHeaderContentLength = header;
            mInfo.mTotalBytes = Long.parseLong(innerState.mHeaderContentLength);
        }
    } else {
        // Ignore content-length with transfer-encoding - 2616 4.4 3
        if (Constants.LOGVV) {
            Log.v(Constants.TAG, "ignoring content-length because of xfer-encoding");
        }
    }
    if (Constants.LOGVV) {
        Log.v(Constants.TAG, "Content-Disposition: " + innerState.mHeaderContentDisposition);
        Log.v(Constants.TAG, "Content-Length: " + innerState.mHeaderContentLength);
        Log.v(Constants.TAG, "Content-Location: " + innerState.mHeaderContentLocation);
        Log.v(Constants.TAG, "Content-Type: " + state.mMimeType);
        Log.v(Constants.TAG, "ETag: " + innerState.mHeaderETag);
        Log.v(Constants.TAG, "Transfer-Encoding: " + headerTransferEncoding);
    }

    boolean noSizeInfo = innerState.mHeaderContentLength == null
            && (headerTransferEncoding == null || !headerTransferEncoding.equalsIgnoreCase("chunked"));
    if (!mInfo.mNoIntegrity && noSizeInfo) {
        throw new StopRequest(Downloads.STATUS_HTTP_DATA_ERROR, "can't know size of download, giving up");
    }
}