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:org.opensilk.music.renderer.googlecast.server.ProxyHandler.java

License:Open Source License

@Override
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    if (!HttpMethods.GET.equals(request.getMethod())) {
        response.sendError(HttpStatus.METHOD_NOT_ALLOWED_405);
        baseRequest.setHandled(true);/*from  ww w .ja  v a  2s  . com*/
        return;
    }

    String pathInfo = StringUtils.stripStart(request.getPathInfo(), "/");
    Uri contentUri = Uri.parse(CastServerUtil.decodeString(pathInfo));

    if (CastServer.DUMP_REQUEST_HEADERS) {
        StringBuilder reqlog = new StringBuilder();
        reqlog.append("Serving artwork uri ").append(contentUri).append("\n Method ")
                .append(request.getMethod());
        for (Enumeration<String> names = request.getHeaderNames(); names.hasMoreElements();) {
            String name = names.nextElement();
            reqlog.append("\n HDR: ").append(name).append(":").append(request.getHeader(name));
        }
        Timber.v(reqlog.toString());
    }

    com.squareup.okhttp.Request.Builder rb = new com.squareup.okhttp.Request.Builder()
            .url(contentUri.toString());
    Track.Res trackRes = mTrackResCache.get(contentUri);

    //add resource headers
    Map<String, String> headers = trackRes.getHeaders();
    for (Map.Entry<String, String> e : headers.entrySet()) {
        rb.addHeader(e.getKey(), e.getValue());
    }

    String range = request.getHeader("Range");
    if (!StringUtils.isEmpty(range)) {
        rb.addHeader("Range", range);
    }

    String ifnonematch = request.getHeader("if-none-match");
    if (!StringUtils.isEmpty(ifnonematch)) {
        rb.addHeader("if-none-match", ifnonematch);
    }

    //dont clog our cache with binaries
    CacheControl pCC = new CacheControl.Builder().noStore().noCache().build();
    rb.cacheControl(pCC);

    Response pResponse = mOkClient.newCall(rb.get().build()).execute();

    if (CastServer.DUMP_REQUEST_HEADERS) {
        StringBuilder sb = new StringBuilder();
        sb.append("Executed proxy GET request uri ").append(contentUri).append("\n Resp: ")
                .append(pResponse.code()).append(",").append(pResponse.message());
        for (String name : pResponse.headers().names()) {
            sb.append("\n HDR: ").append(name).append(": ").append(pResponse.header(name));
        }
        Timber.v(sb.toString());
    }

    if (!pResponse.isSuccessful()) {
        response.sendError(pResponse.code(), pResponse.message());
        baseRequest.setHandled(true);
        return;
    }

    //build the response
    String acceptRanges = pResponse.header("Accept-Ranges");
    if (!StringUtils.isEmpty(acceptRanges)) {
        response.addHeader("Accept-Ranges", acceptRanges);
    }
    String contentRange = pResponse.header("Content-Range");
    if (!StringUtils.isEmpty(contentRange)) {
        response.addHeader("Content-Range", contentRange);
    }
    String contentLen = pResponse.header("Content-Length");
    if (!StringUtils.isEmpty(contentLen)) {
        response.addHeader("Content-Length", contentLen);
    }
    String contentType = pResponse.header("Content-Type");
    if (StringUtils.isEmpty(contentType)) {
        contentType = "application/octet-stream";
    }
    response.addHeader("Content-Type", contentType);
    String etag = pResponse.header("Etag");
    if (!StringUtils.isEmpty(etag)) {
        response.addHeader("Etag", etag);
    }
    if (HttpStatus.NOT_MODIFIED_304 == pResponse.code()) {
        response.flushBuffer();
    } else {
        InputStream in = pResponse.body().byteStream();
        try {
            //XXX out need not be closed
            OutputStream out = response.getOutputStream();
            IOUtils.copy(in, out);
            out.flush();
        } finally {
            IOUtils.closeQuietly(in);
        }
    }
    baseRequest.setHandled(true);
}

From source file:org.quantumbadger.redreader.http.okhttp.OKHTTPBackend.java

License:Open Source License

@Override
public Request prepareRequest(final Context context, final RequestDetails details) {

    final com.squareup.okhttp.Request.Builder builder = new com.squareup.okhttp.Request.Builder();

    builder.header("User-Agent", Constants.ua(context));

    final List<PostField> postFields = details.getPostFields();

    if (postFields != null) {
        builder.post(RequestBody.create(MediaType.parse("application/x-www-form-urlencoded"),
                PostField.encodeList(postFields)));

    } else {//w  w  w. ja  v a  2 s  .  c om
        builder.get();
    }

    builder.url(details.getUrl().toString());
    builder.cacheControl(CacheControl.FORCE_NETWORK);

    final AtomicReference<Call> callRef = new AtomicReference<>();

    return new Request() {

        public void executeInThisThread(final Listener listener) {

            final Call call = mClient.newCall(builder.build());
            callRef.set(call);

            try {

                final Response response;

                try {
                    response = call.execute();
                } catch (IOException e) {
                    listener.onError(CacheRequest.REQUEST_FAILURE_CONNECTION, e, null);
                    return;
                }

                final int status = response.code();

                if (status == 200 || status == 202) {

                    final ResponseBody body = response.body();
                    final InputStream bodyStream;
                    final Long bodyBytes;

                    if (body != null) {
                        bodyStream = body.byteStream();
                        bodyBytes = body.contentLength();

                    } else {
                        // TODO error
                        bodyStream = null;
                        bodyBytes = null;
                    }

                    final String contentType = response.header("Content-Type");

                    listener.onSuccess(contentType, bodyBytes, bodyStream);

                } else {
                    listener.onError(CacheRequest.REQUEST_FAILURE_REQUEST, null, status);
                }

            } catch (Throwable t) {
                listener.onError(CacheRequest.REQUEST_FAILURE_CONNECTION, t, null);
            }
        }

        @Override
        public void cancel() {
            final Call call = callRef.getAndSet(null);
            if (call != null) {
                call.cancel();
            }
        }

        @Override
        public void addHeader(final String name, final String value) {
            builder.addHeader(name, value);
        }
    };
}

From source file:org.runbuddy.libtomahawk.resolver.ScriptResolver.java

License:Open Source License

public Promise<String, Throwable, Void> getStreamUrl(final Result result) {
    final ADeferredObject<String, Throwable, Void> deferred = new ADeferredObject<>();
    if (result != null) {
        HashMap<String, Object> args = new HashMap<>();
        args.put("url", result.getPath());
        ScriptJob.start(mScriptObject, "getStreamUrl", args,
                new ScriptJob.ResultsCallback<ScriptResolverStreamUrlResult>(
                        ScriptResolverStreamUrlResult.class) {
                    @Override/*from w  w w .jav a 2  s . co m*/
                    public void onReportResults(ScriptResolverStreamUrlResult results) {
                        Response response = null;
                        try {
                            if (results.headers != null) {
                                // If headers are given we first have to resolve the url that
                                // the call is being redirected to
                                response = NetworkUtils.httpRequest("GET", results.url, results.headers, null,
                                        null, null, false, null);
                                deferred.resolve(response.header("Location"));
                            } else {
                                deferred.resolve(results.url);
                            }
                        } catch (IOException e) {
                            Log.e(TAG, "reportStreamUrl: " + e.getClass() + ": " + e.getLocalizedMessage());
                            deferred.reject(e);
                        } finally {
                            if (response != null) {
                                try {
                                    response.body().close();
                                } catch (IOException e) {
                                    Log.e(TAG,
                                            "getStreamUrl: " + e.getClass() + ": " + e.getLocalizedMessage());
                                }
                            }
                        }
                    }
                }, new ScriptJob.FailureCallback() {
                    @Override
                    public void onReportFailure(String errormessage) {
                        deferred.reject(new Throwable(errormessage));
                    }
                });
    } else {
        deferred.reject(new Throwable("result is null"));
    }
    return deferred;
}

From source file:twitter4j.AlternativeHttpClientImpl.java

License:Apache License

@Override
HttpResponse handleRequest(HttpRequest req) throws TwitterException {
    prepareOkHttpClient();/*  w  ww. j av  a2  s  .co  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:twitter4j.OkHttpResponse.java

License:Apache License

public OkHttpResponse(Response response, HttpClientConfiguration conf) throws IOException {
    super(conf);/*from   w  ww  .  ja v  a 2  s . c o m*/
    this.response = response;

    Headers headers = response.headers();
    Set<String> names = headers.names();
    HashMap<String, List<String>> headerFields = new HashMap<String, List<String>>();
    for (String name : names) {
        headerFields.put(name, headers.values(name));
    }
    this.headerFields = headerFields;

    is = response.body().byteStream();
    if (is != null && "gzip".equals(response.header("Content-Encoding"))) {
        is = new StreamingGZIPInputStream(is);
    }

    statusCode = response.code();
}