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:keywhiz.UiAssetsBundleTest.java

License:Apache License

@Test
public void uiContentAccessible() throws Exception {
    Request request = new Request.Builder().url(testUrl("/ui/")).get().build();

    Response response = client.newCall(request).execute();
    assertThat(response.code()).isEqualTo(200);
}

From source file:keywhiz.UiAssetsBundleTest.java

License:Apache License

@Test
public void rootRedirects() throws Exception {
    Request request = new Request.Builder().url(testUrl("/")).get().build();

    Response response = client.newCall(request).execute();
    assertThat(response.code()).isEqualTo(302);
    String locationHeader = response.header(HttpHeaders.LOCATION);
    assertThat(locationHeader).endsWith("/ui/");
}

From source file:keywhiz.UiAssetsBundleTest.java

License:Apache License

@Test
public void incompleteUiRedirects() throws Exception {
    Request request = new Request.Builder().url(testUrl("/ui")).get().build();

    Response response = client.newCall(request).execute();
    assertThat(response.code()).isEqualTo(302);
    String locationHeader = response.header(HttpHeaders.LOCATION);
    assertThat(locationHeader).endsWith("/ui/");
}

From source file:library.util.OkHttpStack.java

License:Apache License

@Override
public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders)
        throws IOException, AuthFailureError {

    OkHttpClient client = mClient.clone();
    int timeoutMs = request.getTimeoutMs();
    client.setConnectTimeout(timeoutMs, TimeUnit.MILLISECONDS);
    client.setReadTimeout(timeoutMs, TimeUnit.MILLISECONDS);
    client.setWriteTimeout(timeoutMs, TimeUnit.MILLISECONDS);

    Builder okHttpRequestBuilder = new Builder();
    okHttpRequestBuilder.url(request.getUrl());

    Map<String, String> headers = request.getHeaders();
    for (final String name : headers.keySet()) {
        okHttpRequestBuilder.addHeader(name, headers.get(name));
    }//from   w  ww  .  j a va  2 s  .co m
    for (final String name : additionalHeaders.keySet()) {
        okHttpRequestBuilder.addHeader(name, additionalHeaders.get(name));
    }

    setConnectionParametersForRequest(okHttpRequestBuilder, request);

    com.squareup.okhttp.Request okHttpRequest = okHttpRequestBuilder.build();
    Call okHttpCall = client.newCall(okHttpRequest);
    Response okHttpResponse = okHttpCall.execute();

    StatusLine responseStatus = new BasicStatusLine(parseProtocol(okHttpResponse.protocol()),
            okHttpResponse.code(), okHttpResponse.message());
    BasicHttpResponse response = new BasicHttpResponse(responseStatus);
    response.setEntity(entityFromOkHttpResponse(okHttpResponse));

    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) {
            response.addHeader(new BasicHeader(name, value));
        }
    }

    return response;
}

From source file:lumbermill.elasticsearch.IndexFailedException.java

License:Apache License

public static IndexFailedException of(Response response) {
    try {/*from w ww . j  a  va2 s  .c om*/
        return new IndexFailedException(response,
                response.code() + ", message:" + response.message() + ", body: " + response.body().string());
    } catch (IOException e) {
        LOGGER.warn("Failed to extract body from error message: " + e.getMessage());
        return new IndexFailedException(response, response.code() + ", message:" + response.message());
    }
}

From source file:lumbermill.internal.elasticsearch.ElasticSearchOkHttpClientImpl.java

License:Apache License

/**
 * Handles the response from OkHttp client to determine if the response was ok, is retryable or not
 * @param request - Used for logging purposed if the request was a 400 BadRequest
 * @param response//from w  w w  .j a  v a  2  s  .co  m
 */
private void handleResponse(RequestContext request, Response response) {

    if (response.code() == 200) {
        ElasticSearchBulkResponse bulkResponse = ElasticSearchBulkResponse.parse(request.signableRequest,
                response);
        if (bulkResponse.hasErrors()) {
            Optional<Observable<RequestContext>> requestContextObservable = request.nextAttempt(bulkResponse);
            if (!requestContextObservable.isPresent()) {
                request.done(bulkResponse);
            } else {
                requestContextObservable.get().doOnNext(requestContext -> post(requestContext))
                        .doOnError(throwable -> request.error(throwable)).subscribe();
            }
        } else {
            request.done(bulkResponse);
        }
        return;
    }

    if (response.code() == 400) {
        request.error(createFatalIndexException(request.signableRequest, response));
        return;
    }

    request.error(IndexFailedException.of(response));
}

From source file:lumbermill.internal.elasticsearch.ElasticSearchOkHttpClientImpl.java

License:Apache License

public static FatalIndexException createFatalIndexException(RequestSigner.SignableRequest request,
        Response response) {
    try {/*from w  w w. j  a va2 s.  c o m*/
        return new FatalIndexException(
                response.code() + ", message:" + response.message() + ", body: " + response.body().string());
    } catch (IOException e) {
        LOGGER.warn("Failed to extract body from error message: " + e.getMessage());
        return new FatalIndexException(response.code() + ", message:" + response.message());
    }
}

From source file:me.calebjones.blogsite.network.PostDownloader.java

License:Apache License

public void download(final List<String> postID) {
    final DatabaseManager databaseManager = new DatabaseManager(this);

    try {//from  w ww  .j  a  v a2  s  .co  m
        final int num = postID.size() - 1;
        final CountDownLatch latch = new CountDownLatch(num);
        final Executor executor = Executors.newFixedThreadPool(15);

        for (int i = 1; i <= postID.size() - 1; i++) {
            final int count = i;
            final int index = Integer.parseInt(postID.get(i));
            executor.execute(new Runnable() {

                @Override
                public void run() {
                    try {
                        if (index != 404) {
                            String url = String.format(POST_URL, index);
                            Request newReq = new Request.Builder().url(url).build();
                            Response newResp = BlogsiteApplication.getInstance().client.newCall(newReq)
                                    .execute();

                            if (!newResp.isSuccessful() && !(newResp.code() == 404)
                                    && !(newResp.code() == 403)) {
                                Log.e("The Jones Theory", "Error: " + newResp.code() + "URL: " + url);
                                LocalBroadcastManager.getInstance(PostDownloader.this)
                                        .sendBroadcast(new Intent(DOWNLOAD_FAIL));
                                throw new IOException();
                            }

                            if (newResp.code() == 404) {
                                return;
                            }

                            String resp = newResp.body().string();

                            JSONObject jObject = new JSONObject(resp);

                            Posts item1 = new Posts();

                            //If the item is not a post break out of loop and ignore it
                            if (!(jObject.optString("type").equals("post"))) {
                                return;
                            }
                            item1.setTitle(jObject.optString("title"));
                            item1.setContent(jObject.optString("content"));
                            item1.setExcerpt(jObject.optString("excerpt"));
                            item1.setPostID(jObject.optInt("ID"));
                            item1.setURL(jObject.optString("URL"));

                            //Parse the Date!
                            String date = jObject.optString("date");
                            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
                            Date newDate = format.parse(date);

                            format = new SimpleDateFormat("yyyy-MM-dd");
                            date = format.format(newDate);

                            item1.setDate(date);

                            //Cuts out all the Child nodes and gets only the  tags.
                            JSONObject Tobj = new JSONObject(jObject.optString("tags"));
                            JSONArray Tarray = Tobj.names();
                            String tagsList = null;

                            if (Tarray != null && (Tarray.length() > 0)) {

                                for (int c = 0; c < Tarray.length(); c++) {
                                    if (tagsList != null) {
                                        String thisTag = Tarray.getString(c);
                                        tagsList = tagsList + ", " + thisTag;
                                    } else {
                                        String thisTag = Tarray.getString(c);
                                        tagsList = thisTag;
                                    }
                                }
                                item1.setTags(tagsList);
                            } else {
                                item1.setTags("");
                            }

                            JSONObject Cobj = new JSONObject(jObject.optString("categories"));
                            JSONArray Carray = Cobj.names();
                            String catsList = null;

                            if (Carray != null && (Carray.length() > 0)) {

                                for (int c = 0; c < Carray.length(); c++) {
                                    if (catsList != null) {
                                        String thisCat = Carray.getString(c);
                                        catsList = catsList + ", " + thisCat;
                                    } else {
                                        String thisCat = Carray.getString(c);
                                        catsList = thisCat;
                                    }
                                }
                                item1.setCategories(catsList);
                            } else {
                                item1.setCategories("");
                            }

                            Integer ImageLength = jObject.optString("featured_image").length();
                            if (ImageLength == 0) {
                                item1.setFeaturedImage(null);
                            } else {
                                item1.setFeaturedImage(jObject.optString("featured_image"));
                            }
                            if (item1 != null) {
                                databaseManager.addPost(item1);
                                Log.d("PostDownloader", index + " database...");
                                double progress = ((double) count / num) * 100;
                                setProgress((int) progress, item1.getTitle(), count);

                                Intent intent = new Intent(DOWNLOAD_PROGRESS);
                                intent.putExtra(PROGRESS, progress);
                                intent.putExtra(NUMBER, num);
                                intent.putExtra(TITLE, item1.getTitle());

                                LocalBroadcastManager.getInstance(PostDownloader.this).sendBroadcast(intent);
                            }
                        }
                    } catch (IOException | JSONException | ParseException e) {
                        if (SharedPrefs.getInstance().isFirstDownload()) {
                            SharedPrefs.getInstance().setFirstDownload(false);
                        }
                        SharedPrefs.getInstance().setDownloading(false);
                        e.printStackTrace();
                    } finally {
                        latch.countDown();
                    }
                }
            });
        }
        try {
            latch.await();
        } catch (InterruptedException e) {
            if (SharedPrefs.getInstance().isFirstDownload()) {
                SharedPrefs.getInstance().setFirstDownload(false);
            }
            SharedPrefs.getInstance().setDownloading(false);
            LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent(DOWNLOAD_FAIL));
            mBuilder.setContentText("Download failed.").setSmallIcon(R.drawable.ic_action_file_download)
                    .setAutoCancel(true).setProgress(0, 0, false).setOngoing(false);
            mNotifyManager.notify(NOTIF_ID, mBuilder.build());
            throw new IOException(e);
        }
        if (SharedPrefs.getInstance().isFirstDownload()) {
            SharedPrefs.getInstance().setFirstDownload(false);
        }
        SharedPrefs.getInstance().setDownloading(false);

        Log.d("PostDownloader", "Broadcast Sent!");
        Log.d("The Jones Theory", "download - Downloading = " + SharedPrefs.getInstance().isDownloading());

        Intent mainActIntent = new Intent(this, MainActivity.class);
        PendingIntent clickIntent = PendingIntent.getActivity(this, 57836, mainActIntent,
                PendingIntent.FLAG_UPDATE_CURRENT);

        LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent(DOWNLOAD_SUCCESS));
        mBuilder.setContentText("Download complete").setSmallIcon(R.drawable.ic_action_done)
                .setProgress(0, 0, false).setContentIntent(clickIntent).setAutoCancel(true).setOngoing(false);
        mNotifyManager.notify(NOTIF_ID, mBuilder.build());

    } catch (IOException e) {
        if (SharedPrefs.getInstance().isFirstDownload()) {
            SharedPrefs.getInstance().setFirstDownload(false);
        }
        SharedPrefs.getInstance().setLastRedownladTime(System.currentTimeMillis());
        SharedPrefs.getInstance().setDownloading(false);
        e.printStackTrace();
        LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent(DOWNLOAD_FAIL));
        mBuilder.setContentText("Download failed.").setProgress(0, 0, false).setAutoCancel(true)
                .setOngoing(false);
        mNotifyManager.notify(NOTIF_ID, mBuilder.build());
    }
}

From source file:microsoft.aspnet.signalr.client.http.android.AndroidOkHttpConnection.java

License:Open Source License

@Override
public HttpConnectionFuture execute(final Request request, final ResponseCallback responseCallback) {

    mLogger.log("Create new AsyncTask for HTTP Connection", LogLevel.Verbose);

    final HttpConnectionFuture future = new HttpConnectionFuture();

    com.squareup.okhttp.Request okHttpRequest = createRequest(request);

    final Call call = client.newCall(okHttpRequest);
    call.enqueue(new Callback() {
        @Override/*from   ww w . j  a  v a2  s  . com*/
        public void onFailure(com.squareup.okhttp.Request request, IOException e) {
            mLogger.log("Error executing request: " + e.getMessage(), LogLevel.Critical);
            future.triggerError(e);
        }

        @Override
        public void onResponse(Response response) throws IOException {
            mLogger.log("Request executed", LogLevel.Verbose);

            InputStream bodyStream = response.body().byteStream();
            Map<String, List<String>> headersMap = response.headers().toMultimap();
            try {
                responseCallback.onResponse(new StreamResponse(bodyStream, response.code(), headersMap));
                future.setResult(null);
            } catch (Exception e) {
                mLogger.log("Error calling onResponse: " + e.getMessage(), LogLevel.Critical);
                future.triggerError(e);
            }
        }
    });

    future.onCancelled(new Runnable() {
        @Override
        public void run() {
            call.cancel();
        }
    });

    return future;
}

From source file:name.kevinlocke.appveyor.testutils.ConcurrentHttpLoggingInterceptor.java

License:Apache License

@Override
public Response intercept(Chain chain) throws IOException {
    Level level = this.level;

    Request request = chain.request();
    if (level == Level.NONE) {
        return chain.proceed(request);
    }/*  w  w  w. ja  v a2s  . c  om*/

    boolean logBody = level == Level.BODY;
    boolean logHeaders = logBody || level == Level.HEADERS;

    RequestBody requestBody = request.body();

    Connection connection = chain.connection();
    Protocol protocol = connection != null ? connection.getProtocol() : Protocol.HTTP_1_1;
    UUID requestId = UUID.randomUUID();
    StringBuilder requestMessage = new StringBuilder("--> ").append(requestId).append('\n')
            .append(request.method()).append(' ').append(request.httpUrl()).append(' ').append(protocol);
    if (!logHeaders && requestBody != null) {
        requestMessage.append(" (").append(requestBody.contentLength()).append("-byte body)");
    }
    requestMessage.append('\n');

    if (logHeaders) {
        if (requestBody != null) {
            // Request body headers are only present when installed as a
            // network interceptor. Force
            // them to be included (when available) so there values are
            // known.
            if (requestBody.contentType() != null) {
                requestMessage.append("Content-Type: ").append(requestBody.contentType()).append('\n');
            }
            if (requestBody.contentLength() != -1) {
                requestMessage.append("Content-Length: ").append(requestBody.contentLength()).append('\n');
            }
        }

        Headers headers = request.headers();
        for (int i = 0, count = headers.size(); i < count; i++) {
            String name = headers.name(i);
            if ("Authorization".equalsIgnoreCase(name) || "Proxy-Authenticate".equalsIgnoreCase(name)
                    || "Proxy-Authorization".equalsIgnoreCase(name)
                    || "WWW-Authenticate".equalsIgnoreCase(name)) {
                requestMessage.append(name).append(": *****\n");
            }
            // Skip headers from the request body as they are explicitly
            // logged above.
            else if (!"Content-Type".equalsIgnoreCase(name) && !"Content-Length".equalsIgnoreCase(name)) {
                requestMessage.append(name).append(": ").append(headers.value(i)).append('\n');
            }
        }

        if (!logBody || requestBody == null) {
            requestMessage.append("--> END ").append(requestId).append('\n');
        } else if (bodyEncoded(request.headers())) {
            requestMessage.append("--> END ").append(requestId).append(" (encoded body omitted)").append('\n');
        } else {
            Buffer buffer = new Buffer();
            requestBody.writeTo(buffer);

            Charset charset = UTF8;
            MediaType contentType = requestBody.contentType();
            if (contentType != null) {
                charset = contentType.charset(UTF8);
            }

            requestMessage.append('\n');
            if (isPlaintext(buffer)) {
                requestMessage.append(buffer.readString(charset)).append("\n--> END ").append(requestId)
                        .append(" (").append(requestBody.contentLength()).append("-byte body)\n");
            } else {
                requestMessage.append("--> END ").append(requestId).append(" (binary ")
                        .append(requestBody.contentLength()).append("-byte body omitted)\n");
            }
        }
    }

    logger.log(requestMessage.substring(0, requestMessage.length() - 1));

    long startNs = System.nanoTime();
    Response response;
    try {
        response = chain.proceed(request);
    } catch (Exception e) {
        logger.log("<-- " + requestId + "HTTP FAILED: " + e);
        throw e;
    }
    long tookMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNs);

    ResponseBody responseBody = response.body();
    long contentLength = responseBody.contentLength();
    StringBuilder responseMessage = new StringBuilder("<-- ").append(requestId).append(' ')
            .append(response.request().url()).append(" (").append(tookMs).append("ms");
    if (!logHeaders) {
        responseMessage.append(", ");
        if (contentLength != -1) {
            responseMessage.append(contentLength).append("-byte");
        } else {
            responseMessage.append("unknown-length");
        }
        responseMessage.append(" body");
    }
    responseMessage.append(")\n");

    responseMessage.append(response.code()).append(' ').append(response.message()).append('\n');

    if (logHeaders) {
        Headers headers = response.headers();
        for (int i = 0, count = headers.size(); i < count; i++) {
            responseMessage.append(headers.name(i)).append(": ").append(headers.value(i)).append('\n');
        }

        if (!logBody || !HttpEngine.hasBody(response)) {
            responseMessage.append("<-- END HTTP\n");
        } else if (bodyEncoded(response.headers())) {
            responseMessage.append("<-- END HTTP (encoded body omitted)\n");
        } else {
            BufferedSource source = responseBody.source();
            source.request(Long.MAX_VALUE); // Buffer the entire body.
            Buffer buffer = source.buffer();

            Charset charset = UTF8;
            MediaType contentType = responseBody.contentType();
            if (contentType != null) {
                charset = contentType.charset(UTF8);
            }

            if (!isPlaintext(buffer)) {
                responseMessage.append('\n').append("<-- END HTTP (binary ").append(buffer.size())
                        .append("-byte body omitted)");
                logger.log(responseMessage.toString());
                return response;
            }

            if (contentLength != 0) {
                responseMessage.append('\n').append(buffer.clone().readString(charset)).append('\n');
            }

            responseMessage.append("<-- END HTTP (").append(buffer.size()).append("-byte body)\n");
        }
    }

    logger.log(responseMessage.substring(0, responseMessage.length() - 1));
    return response;
}