Example usage for com.squareup.okhttp Response body

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

Introduction

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

Prototype

ResponseBody body

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

Click Source Link

Usage

From source file:com.github.automately.sdk.Automately.java

License:Mozilla Public License

public static JsonObject findModule(String moduleName) {
    try {//www  .  j  a v a 2 s.c o m

        // TODO Include credentials to allow for the searching of private user modules
        Request request = new Request.Builder().url(REGISTRY_ENDPOINT + "/retrieve?name=" + moduleName).get()
                .build();

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

        if (response != null) {
            String responseEntity = response.body().string();
            try {
                checkAuthorized(responseEntity);
                return new JsonObject(responseEntity);
            } catch (DecodeException ignored) {
                getFormattedError("Decode Exception", "There was an issue decoding the response.");
            }
        }
    } catch (IOException ignored) {
    }
    return null;
}

From source file:com.github.drrb.surefiresplitter.go.GoServer.java

License:Open Source License

private ResponseBody get(String url) throws CommunicationError {
    Request.Builder requestBuilder = new Request.Builder().get().url(url);
    if (username != null && password != null) {
        requestBuilder.addHeader("Authorization", Credentials.basic(username, password));
    }/* w w w.  j av  a  2 s . c  o  m*/
    Response response = execute(requestBuilder.build());
    if (response.isSuccessful()) {
        return response.body();
    } else {
        String errorMessage = String.format("Bad status code when requesting: %s (%d: %s)", url,
                response.code(), response.message());
        try (ResponseBody responseBody = response.body()) {
            errorMessage += ("\n" + responseBody.string());
        } catch (IOException e) {
            errorMessage += ". Tried to read the response body for a helpful message, but couldn't (Error was '"
                    + e.getMessage() + "').";
        }
        throw new CommunicationError(errorMessage);
    }
}

From source file:com.github.drrb.surefiresplitter.go.GoServer.java

License:Open Source License

private Response execute(Request request) throws CommunicationError {
    System.out.println(" -> " + request.url());
    try {//  w  w  w .  j  a va2s .  c o  m
        Response response = httpClient.newCall(request).execute();
        System.out.println(" <- " + response.code() + ": " + response.message() + " ("
                + Bytes.render(response.body().contentLength()) + ")");
        return response;
    } catch (IOException e) {
        throw new CommunicationError("Connection to Go server failed", e);
    }
}

From source file:com.github.leonardoxh.temporeal.app.service.NoticeService.java

License:Apache License

@Override
protected void onHandleIntent(Intent intent) {
    Response response = makeRequest(Constants.NOTICE_ENDPOINT, null);
    if (response.isSuccessful()) {
        try {/*from w w  w  . ja v  a  2  s  .  co  m*/
            List<Notice> notices = JsonUtils.listFromJson(response.body().string(), Notice.class);
            if (!notices.isEmpty()) {
                NoticeDao noticeDao = new NoticeDao(this);
                noticeDao.saveAllNotices(notices);
            }
        } catch (IOException e) {
            /* Podemos simplesmente ignorar essa exception
             * por que teremos uma falha de leitura, entao na
             * proxima sincronizacao tudo sera sincronizado */
            e.printStackTrace();
        }
    }
}

From source file:com.github.leonardoxh.temporeal.app.service.UserService.java

License:Apache License

@Override
protected void onHandleIntent(Intent intent) {
    User user = intent.getExtras().getParcelable(EXTRA_USER);
    Response response = makeRequest(Constants.USER_ENDPOINT, user);
    if (response.isSuccessful()) {
        try {/*from   w  w w  .j av  a2 s.  c  om*/
            User serverUser = JsonUtils.fromJson(response.body().string(), User.class);
            /* O usuario foi cadastrado no servidor corretamente, entao so persistimos ele
             * e indicamos a nossa Activity o sucesso do mesmo */
            new UserDao(this).saveOrUpdate(serverUser);
            sendSuccess(serverUser);
        } catch (IOException e) {
            /* Essa exception sera lancada caso tenhamos alguma falha na
             * leitura da resposta do servidor */
            e.printStackTrace();
            sendFailure();
        }
    } else {
        sendFailure();
    }
}

From source file:com.github.mmatczuk.ablb.benchmark.OkHttpAsync.java

License:Apache License

@Override
public void prepare(final Benchmark benchmark) {
    concurrencyLevel = benchmark.concurrencyLevel;
    targetBacklog = benchmark.targetBacklog;

    client = new OkHttpClient();
    client.setDispatcher(new Dispatcher(new ThreadPoolExecutor(benchmark.concurrencyLevel,
            benchmark.concurrencyLevel, 60, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>())));

    callback = new Callback() {
        @Override/*  w  w w.  ja va2 s . c  o  m*/
        public void onFailure(Request request, IOException e) {
            System.out.println("Failed: " + e);
        }

        @Override
        public void onResponse(Response response) throws IOException {
            ResponseBody body = response.body();
            long total = readAllAndClose(body.byteStream());
            long finish = System.nanoTime();
            if (VERBOSE) {
                long start = (Long) response.request().tag();
                System.out.printf("Transferred % 8d bytes in %4d ms%n", total,
                        TimeUnit.NANOSECONDS.toMillis(finish - start));
            }
            requestsInFlight.decrementAndGet();
        }
    };
}

From source file:com.github.mobile.util.HttpImageGetter.java

License:Apache License

@Override
public Drawable getDrawable(final String source) {
    try {//from  w w w.  j  a va 2  s .com
        Drawable repositoryImage = requestRepositoryImage(source);
        if (repositoryImage != null)
            return repositoryImage;
    } catch (Exception e) {
        // Ignore and attempt request over regular HTTP request
    }

    if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.FROYO) {
        return loading.getDrawable(source);
    }

    try {
        Request request = new Request.Builder().url(source).build();
        OkHttpClient client = new OkHttpClient();
        Response response = client.newCall(request).execute();

        Bitmap bitmap = ImageUtils.getBitmap(response.body().bytes(), width, MAX_VALUE);
        if (bitmap == null)
            return loading.getDrawable(source);
        BitmapDrawable drawable = new BitmapDrawable(context.getResources(), bitmap);
        drawable.setBounds(0, 0, bitmap.getWidth(), bitmap.getHeight());
        return drawable;
    } catch (IOException e) {
        return loading.getDrawable(source);
    }
}

From source file:com.github.pockethub.android.ui.comment.RawCommentFragment.java

License:Apache License

@Override
public void onActivityResult(final int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == REQUEST_CODE_SELECT_PHOTO && resultCode == Activity.RESULT_OK) {
        showProgressIndeterminate(R.string.loading);
        ImageBinPoster.post(getActivity(), data.getData(), new Callback() {
            @Override/*from w w w  .  ja  va2 s  .co m*/
            public void onFailure(Request request, IOException e) {
                dismissProgress();
                showImageError();
            }

            @Override
            public void onResponse(Response response) throws IOException {
                dismissProgress();
                if (response.isSuccessful()) {
                    insertImage(ImageBinPoster.getUrl(response.body().string()));
                } else {
                    showImageError();
                }
            }
        });
    }
}

From source file:com.github.pockethub.android.util.HttpImageGetter.java

License:Apache License

@Override
public Drawable getDrawable(final String source) {
    try {/*from   w w  w .  j ava  2 s .c  om*/
        Drawable repositoryImage = requestRepositoryImage(source);
        if (repositoryImage != null)
            return repositoryImage;
    } catch (Exception e) {
        // Ignore and attempt request over regular HTTP request
    }

    try {
        String logMessage = "Loading image: " + source;
        Log.d(getClass().getSimpleName(), logMessage);
        Bugsnag.leaveBreadcrumb(logMessage);

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

        com.squareup.okhttp.Response response = okHttpClient.newCall(request).execute();

        if (!response.isSuccessful())
            throw new IOException("Unexpected response code: " + response.code());

        Bitmap bitmap = BitmapFactory.decodeStream(response.body().byteStream());

        if (bitmap == null)
            return loading.getDrawable(source);

        BitmapDrawable drawable = new BitmapDrawable(context.getResources(), bitmap);
        drawable.setBounds(0, 0, bitmap.getWidth(), bitmap.getHeight());
        return drawable;
    } catch (IOException e) {
        Log.e(getClass().getSimpleName(), "Error loading image", e);
        Bugsnag.notify(e);
        return loading.getDrawable(source);
    }
}

From source file:com.github.radium226.common.Ok.java

License:Apache License

public static InputStream download(OkHttpClient httpClient, String url) throws IOException {
    Request request = new Request.Builder().url(url).build();
    Response response = httpClient.newCall(request).execute();
    InputStream bodyInputStream = response.body().byteStream();
    return bodyInputStream;
}