Example usage for com.squareup.okhttp Response message

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

Introduction

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

Prototype

String message

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

Click 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);/*w w w  . j  a  v a2  s . c om*/
        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.runbuddy.libtomahawk.resolver.ScriptAccount.java

License:Open Source License

private JsonObject jsHttpRequest(ScriptInterfaceRequestOptions options) {
    Response response = null;
    try {//www .jav a  2 s . c  o m
        String url = null;
        Map<String, String> headers = null;
        String method = null;
        String username = null;
        String password = null;
        String data = null;
        boolean isTestingConfig = false;
        if (options != null) {
            url = options.url;
            headers = options.headers;
            method = options.method;
            username = options.username;
            password = options.password;
            data = options.data;
            isTestingConfig = options.isTestingConfig;
        }
        java.net.CookieManager cookieManager = getCookieManager(isTestingConfig);
        response = NetworkUtils.httpRequest(method, url, headers, username, password, data, true,
                cookieManager);
        // We have to encode the %-chars because the Android WebView automatically decodes
        // percentage-escaped chars ... for whatever reason. Seems likely that this is a bug.
        String responseText = response.body().string().replace("%", "%25");
        JsonObject responseHeaders = new JsonObject();
        for (String headerName : response.headers().names()) {
            String concatenatedValues = "";
            for (int i = 0; i < response.headers(headerName).size(); i++) {
                if (i > 0) {
                    concatenatedValues += "\n";
                }
                concatenatedValues += response.headers(headerName).get(i);
            }
            String escapedKey = headerName.toLowerCase().replace("%", "%25");
            String escapedValue = concatenatedValues.replace("%", "%25");
            responseHeaders.addProperty(escapedKey, escapedValue);
        }
        int status = response.code();
        String statusText = response.message().replace("%", "%25");

        JsonObject result = new JsonObject();
        result.addProperty("responseText", responseText);
        result.add("responseHeaders", responseHeaders);
        result.addProperty("status", status);
        result.addProperty("statusText", statusText);
        return result;
    } catch (IOException e) {
        Log.e(TAG, "jsHttpRequest: " + e.getClass() + ": " + e.getLocalizedMessage());
        return null;
    } finally {
        if (response != null) {
            try {
                response.body().close();
            } catch (IOException e) {
                Log.e(TAG, "jsHttpRequest: " + e.getClass() + ": " + e.getLocalizedMessage());
            }
        }
    }
}

From source file:org.whispersystems.signalservice.internal.push.PushServiceSocket.java

private String makeRequest(String urlFragment, String method, String body)
        throws NonSuccessfulResponseCodeException, PushNetworkException {
    Response response = getConnection(urlFragment, method, body);

    int responseCode;
    String responseMessage;//  w w  w .j a  v  a2 s.com
    String responseBody;

    try {
        responseCode = response.code();
        responseMessage = response.message();
        responseBody = response.body().string();
    } catch (IOException ioe) {
        throw new PushNetworkException(ioe);
    }

    switch (responseCode) {
    case 413:
        throw new RateLimitException("Rate limit exceeded: " + responseCode);
    case 401:
    case 403:
        throw new AuthorizationFailedException("Authorization failed!");
    case 404:
        throw new NotFoundException("Not found");
    case 409:
        MismatchedDevices mismatchedDevices;

        try {
            mismatchedDevices = JsonUtil.fromJson(responseBody, MismatchedDevices.class);
        } catch (JsonProcessingException e) {
            Log.w(TAG, e);
            throw new NonSuccessfulResponseCodeException(
                    "Bad response: " + responseCode + " " + responseMessage);
        } catch (IOException e) {
            throw new PushNetworkException(e);
        }

        throw new MismatchedDevicesException(mismatchedDevices);
    case 410:
        StaleDevices staleDevices;

        try {
            staleDevices = JsonUtil.fromJson(responseBody, StaleDevices.class);
        } catch (JsonProcessingException e) {
            throw new NonSuccessfulResponseCodeException(
                    "Bad response: " + responseCode + " " + responseMessage);
        } catch (IOException e) {
            throw new PushNetworkException(e);
        }

        throw new StaleDevicesException(staleDevices);
    case 411:
        DeviceLimit deviceLimit;

        try {
            deviceLimit = JsonUtil.fromJson(responseBody, DeviceLimit.class);
        } catch (JsonProcessingException e) {
            throw new NonSuccessfulResponseCodeException(
                    "Bad response: " + responseCode + " " + responseMessage);
        } catch (IOException e) {
            throw new PushNetworkException(e);
        }

        throw new DeviceLimitExceededException(deviceLimit);
    case 417:
        throw new ExpectationFailedException();
    }

    if (responseCode != 200 && responseCode != 204) {
        throw new NonSuccessfulResponseCodeException("Bad response: " + responseCode + " " + responseMessage);
    }

    return responseBody;
}

From source file:quickbeer.android.next.network.utils.LoginRedirectInterceptor.java

License:Open Source License

@Override
public Response intercept(Chain chain) throws IOException {
    Request request = chain.request();
    Response response = chain.proceed(request);

    if (request.uri().getPath().equals("/Signin_r.asp") && response.isRedirect()) {
        Log.d(TAG, "Modifying response for login request");

        return new Response.Builder().request(request).protocol(response.protocol()).code(200)
                .message(response.message()).handshake(response.handshake()).headers(response.headers())
                .body(response.body()).networkResponse(response.networkResponse()).build();
    }/*from w w  w. j  av  a 2s  . c  om*/

    return response;
}

From source file:retrofit.RetrofitError.java

License:Apache License

public static RetrofitError httpError(Response response, Converter converter, Type successType) {
    String message = response.code() + " " + response.message();
    return new RetrofitError(message, response.request().urlString(), response, converter, successType,
            Kind.HTTP, null);//from w w  w .  j  a v a  2 s  .  c  o  m
}

From source file:uk.co.caprica.brue.okhttp.service.bridge.AbstractBridgeService.java

License:Open Source License

/**
 * Execute a request, synchronously./*from   w  ww .  j ava  2s .co m*/
 *
 * @param request
 * @param responseType
 * @param <T>
 * @return
 */
private <T> T executeRequest(Request request, JavaType responseType) {
    try {
        Response response = httpClient.newCall(request).execute();
        if (response.isSuccessful()) {
            if (responseType != null) {
                return response(response, responseType);
            } else {
                return null;
            }
        } else {
            throw new BridgeResponseException(response.code(), response.message());
        }
    } catch (IOException e) {
        throw new BridgeIOException(e);
    }
}