Example usage for com.squareup.okhttp Response code

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

Introduction

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

Prototype

int code

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

Click Source Link

Usage

From source file:org.jboss.arquillian.ce.proxy.AbstractProxy.java

License:Open Source License

public <T> T post(String url, Class<T> returnType, Object requestObject) throws Exception {
    final OkHttpClient httpClient = getHttpClient();

    Request.Builder builder = new Request.Builder();
    builder.url(url);//from ww  w . j a  v  a2 s.c  o m

    if (requestObject != null) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try (ObjectOutputStream oos = new ObjectOutputStream(baos)) {
            oos.writeObject(requestObject);
            oos.flush();
        } catch (Exception e) {
            throw new RuntimeException("Error sending request Object, " + requestObject, e);
        }
        RequestBody body = RequestBody.create(MediaType.parse("application/octet-stream"), baos.toByteArray());
        builder.post(body);
    }

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

    int responseCode = response.code();

    if (responseCode == HttpURLConnection.HTTP_OK) {
        Object o;
        try (ObjectInputStream ois = new ObjectInputStream(response.body().byteStream())) {
            o = ois.readObject();
        }

        if (returnType.isInstance(o) == false) {
            throw new IllegalStateException(
                    "Error reading results, expected a " + returnType.getName() + " but got " + o);
        }

        return returnType.cast(o);
    } else if (responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
        return null;
    } else if (responseCode != HttpURLConnection.HTTP_NOT_FOUND) {
        throw new IllegalStateException(
                "Error launching test at " + url + ". Got " + responseCode + " (" + response.message() + ")");
    }

    return null; // TODO
}

From source file:org.jboss.arquillian.ce.proxy.AbstractProxy.java

License:Open Source License

public int status(String url) {
    try {//from www.j av a 2  s.c  o  m
        OkHttpClient httpClient = getHttpClient();
        Request request = new Request.Builder().url(url).build();
        Response response = httpClient.newCall(request).execute();
        return response.code();
    } catch (Exception e) {
        throw new IllegalStateException(e);
    }
}

From source file:org.jclouds.http.okhttp.OkHttpCommandExecutorService.java

License:Apache License

@Override
protected HttpResponse invoke(Request nativeRequest) throws IOException, InterruptedException {
    OkHttpClient requestScopedClient = globalClient.clone();
    requestScopedClient.setProxy(proxyForURI.apply(nativeRequest.uri()));

    Response response = requestScopedClient.newCall(nativeRequest).execute();

    HttpResponse.Builder<?> builder = HttpResponse.builder();
    builder.statusCode(response.code());
    builder.message(response.message());

    Builder<String, String> headerBuilder = ImmutableMultimap.builder();
    Headers responseHeaders = response.headers();
    for (String header : responseHeaders.names()) {
        headerBuilder.putAll(header, responseHeaders.values(header));
    }//  w w w. j  a v  a 2s.  c  o  m

    ImmutableMultimap<String, String> headers = headerBuilder.build();

    if (response.code() == 204 && response.body() != null) {
        response.body().close();
    } else {
        Payload payload = newInputStreamPayload(response.body().byteStream());
        contentMetadataCodec.fromHeaders(payload.getContentMetadata(), headers);
        builder.payload(payload);
    }

    builder.headers(filterOutContentHeaders(headers));

    return builder.build();
}

From source file:org.kegbot.api.KegbotApiImpl.java

License:Open Source License

private JsonNode requestJson(Request request) throws KegbotApiException {
    final Response response;
    final long startTime = SystemClock.elapsedRealtime();
    try {/*from  www.j  a va 2s  .c  om*/
        response = mClient.newCall(request).execute();
    } catch (IOException e) {
        Log.w(TAG, String.format("--> %s %s [ERR]", request.method(), request.urlString()));
        throw new KegbotApiException(e);
    }
    final long endTime = SystemClock.elapsedRealtime();

    final int responseCode = response.code();
    final String logMessage = String.format("--> %s %s [%s] %sms", request.method(), request.urlString(),
            responseCode, endTime - startTime);
    if (responseCode >= 200 && responseCode < 300) {
        Log.d(TAG, logMessage);
    } else {
        Log.w(TAG, logMessage);
    }
    final ResponseBody body = response.body();

    final JsonNode rootNode;
    try {
        try {
            final ObjectMapper mapper = new ObjectMapper();
            rootNode = mapper.readValue(body.byteStream(), JsonNode.class);
        } finally {
            body.close();
        }
    } catch (JsonParseException e) {
        throw new KegbotApiMalformedResponseException(e);
    } catch (JsonMappingException e) {
        throw new KegbotApiMalformedResponseException(e);
    } catch (IOException e) {
        throw new KegbotApiException(e);
    }

    boolean success = false;
    try {
        // Handle structural errors.
        if (!rootNode.has("meta")) {
            throw new KegbotApiMalformedResponseException("Response is missing 'meta' field.");
        }
        final JsonNode meta = rootNode.get("meta");
        if (!meta.isContainerNode()) {
            throw new KegbotApiMalformedResponseException("'meta' field is wrong type.");
        }

        final String message;
        if (rootNode.has("error") && rootNode.get("error").has("message")) {
            message = rootNode.get("error").get("message").getTextValue();
        } else {
            message = null;
        }

        // Handle HTTP errors.
        if (responseCode < 200 || responseCode >= 400) {
            switch (responseCode) {
            case 401:
                throw new NotAuthorizedException(message);
            case 404:
                throw new KegbotApi404(message);
            case 405:
                throw new MethodNotAllowedException(message);
            default:
                if (message != null) {
                    throw new KegbotApiServerError(message);
                } else {
                    throw new KegbotApiServerError("Server error, response code=" + responseCode);
                }
            }
        }

        success = true;
        return rootNode;
    } finally {
        if (!success) {
            Log.d(TAG, "Response JSON was: " + rootNode.toString());
        }
    }
}

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 w ww . jav  a 2 s.c o m*/
        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 {/*from w ww .ja v a 2 s  . co  m*/
        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.robovm.store.util.ImageCache.java

License:Apache License

private File downloadImage(String url, boolean retryOnFail) {
    Objects.requireNonNull(saveLocation, "Must specify a save location!");
    Objects.requireNonNull(url, "url");

    File destination = new File(saveLocation, FilenameUtils.getName(url));
    if (destination.exists()) {
        return destination;
    }//from  www .j  ava2 s. c  om

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

    try {
        Response response = client.newCall(request).execute();
        int code = response.code();
        if (code >= 200 && code < 300) { // Success
            InputStream in = response.body().byteStream();
            FileUtils.copyInputStreamToFile(in, destination);
            return destination;
        } else if (retryOnFail) { // Error
            return downloadImage(PLACEHOLDER_URL, false);
        }
    } catch (IOException e) {
        System.err.println("file download failed: " + e.getMessage());
        if (retryOnFail) {
            return downloadImage(PLACEHOLDER_URL, false);
        }
    }
    return null;
}

From source file:org.robovm.store.util.ImageCache.java

License:Apache License

private void downloadImage(String url, Action<File> completion, boolean retryOnFail) {
    Objects.requireNonNull(saveLocation, "Must specify a save location!");
    Objects.requireNonNull(url, "url");
    Objects.requireNonNull(completion, "completion");

    File destination = new File(saveLocation, FilenameUtils.getName(url));
    if (destination.exists()) {
        ActionWrapper.WRAPPER.invoke(completion, destination);
        return;// w w w .  j  a  va2  s.  co m
    }

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

    client.newCall(request).enqueue(new Callback() {
        @Override
        public void onResponse(Response response) throws IOException {
            int code = response.code();
            if (code >= 200 && code < 300) { // Success
                InputStream in = response.body().byteStream();
                FileUtils.copyInputStreamToFile(in, destination);
                ActionWrapper.WRAPPER.invoke(completion, destination);
            } else if (retryOnFail) { // Error
                downloadImage(PLACEHOLDER_URL, completion, false);
            } else {
                ActionWrapper.WRAPPER.invoke(completion, null);
            }
        }

        @Override
        public void onFailure(Request request, IOException e) {
            System.err.println("file download failed: " + e.getMessage());
            if (retryOnFail) {
                downloadImage(PLACEHOLDER_URL, completion, false);
            } else {
                ActionWrapper.WRAPPER.invoke(completion, null);
            }
        }
    });
}

From source file:org.runbuddy.libtomahawk.infosystem.hatchet.Store.java

License:Open Source License

public JsonElement get(JsonObject object, String memberName) throws IOException {
    JsonElement element = object.get(memberName);
    if (element == null) {
        JsonObject links = object.getAsJsonObject("links");
        if (links != null && links.has(memberName)) {
            Request request = new Request.Builder().url(HATCHET_BASE_URL + links.get(memberName).getAsString())
                    .build();//from ww w .  j a  v  a2 s.  c  o  m
            Log.d(TAG, "following link: " + request.urlString());
            Response response = mOkHttpClient.newCall(request).execute();
            if (!response.isSuccessful()) {
                throw new IOException("API request with URL '" + request.urlString()
                        + "' not successful. Code was " + response.code());
            }
            try {
                element = GsonHelper.get().fromJson(response.body().charStream(), JsonElement.class);
            } catch (JsonIOException | JsonSyntaxException e) {
                throw new IOException(e);
            } finally {
                response.body().close();
            }
        }
    }
    return element;
}

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

License:Open Source License

private JsonObject jsHttpRequest(ScriptInterfaceRequestOptions options) {
    Response response = null;
    try {//ww w  . j  av  a  2s  . c  om
        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());
            }
        }
    }
}