Example usage for com.squareup.okhttp Response isSuccessful

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

Introduction

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

Prototype

public boolean isSuccessful() 

Source Link

Document

Returns true if the code is in [200..300), which means the request was successfully received, understood, and accepted.

Usage

From source file:com.northernwall.hadrian.details.simple.SimpleHostDetailsHelper.java

License:Apache License

private void getDetailsFromUrl(Host host, String url, List<GetPairData> pairs) {
    Request httpRequest = new Request.Builder().url(url).build();
    try {// w  ww.j  a v  a  2 s  . c  om
        Response resp = client.newCall(httpRequest).execute();
        try (Reader reader = new InputStreamReader(resp.body().byteStream())) {
            if (resp.isSuccessful()) {
                JsonElement jsonElement = parser.parse(reader);
                if (jsonElement.isJsonObject()) {
                    JsonObject jsonObject = jsonElement.getAsJsonObject();
                    for (Map.Entry<String, JsonElement> entry : jsonObject.entrySet()) {
                        processAttribute(null, entry, pairs);
                    }
                }
            } else {
                logger.warn("Call to {} failed with code {}", url, resp.code());
            }
        }
    } catch (Exception ex) {
        logger.warn("Error while getting secondary host details for {}, error {}", host.getHostName(),
                ex.getMessage());
    }
}

From source file:com.northernwall.hadrian.service.DocumentGetHandler.java

License:Apache License

@Override
public void handle(String target, Request request, HttpServletRequest httpRequest, HttpServletResponse response)
        throws IOException, ServletException {
    Service service = getService(request);

    for (Document doc : service.getDocuments()) {
        if (doc.getDocId().equals(request.getParameter("docId"))) {
            com.squareup.okhttp.Request docRequest = new com.squareup.okhttp.Request.Builder()
                    .url(addToken(doc.getLink())).build();
            try {
                com.squareup.okhttp.Response resp = client.newCall(docRequest).execute();
                if (resp.isSuccessful()) {
                    try (InputStream inputStream = resp.body().byteStream()) {
                        byte[] buffer = new byte[50 * 1024];
                        int len = inputStream.read(buffer);
                        while (len != -1) {
                            response.getOutputStream().write(buffer, 0, len);
                            len = inputStream.read(buffer);
                        }//from ww  w.j  av a2s  .com
                        response.getOutputStream().flush();
                    }
                    response.setStatus(200);
                    request.setHandled(true);
                    return;
                } else {
                    throw new Http400BadRequestException("Could not get document " + doc.getTitle() + " at "
                            + doc.getLink() + " status " + resp.code());
                }
            } catch (UnknownHostException ex) {
                throw new Http400BadRequestException("Error: Unknown host!");
            } catch (ConnectException | SocketTimeoutException ex) {
                throw new Http400BadRequestException("Error: Time out!");
            }
        }
    }

    throw new Http400BadRequestException("Could not find document");
}

From source file:com.northernwall.hadrian.workItem.simple.SimpleWorkItemSender.java

License:Apache License

@Override
public Result sendWorkItem(WorkItem workItem) throws IOException {
    RequestBody body = RequestBody.create(Const.JSON_MEDIA_TYPE, gson.toJson(workItem));
    Request request = new Request.Builder().url(url).addHeader("X-Request-Id", workItem.getId()).post(body)
            .build();/*  ww  w . j  ava2  s.c  om*/
    Response response = client.newCall(request).execute();
    logger.info("Sent workitem {} and got response {}", workItem.getId(), response.code());
    if (response.isSuccessful()) {
        return Result.wip;
    }
    return Result.error;
}

From source file:com.nuvolect.securesuite.webserver.Comm.java

License:Open Source License

/**
 * Send a post message./*  w ww  .j  av  a2  s . c o  m*/
 * @param url
 * @param params
 * @param listener
 */
public static void sendPost(String url, final Map<String, String> params, CommPostCallbacks listener) {

    String postBody = "";
    String amphersand = "";

    OkHttpClient okHttpClient = WebService.getOkHttpClient();

    for (Map.Entry<String, String> entry : params.entrySet()) {

        postBody += amphersand;
        postBody += entry.getKey();
        postBody += "=";
        postBody += entry.getValue();
        amphersand = "&";
    }

    Request request = new Request.Builder().url(url).post(RequestBody.create(MEDIA_TYPE_MARKDOWN, postBody))
            .header(CConst.SEC_TOK, CrypServer.getSecTok()).build();

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

        if (listener != null && response.isSuccessful()) {

            listener.success(response.body().string());
        } else {

            if (listener != null)
                listener.fail("Unexpected code " + response);
        }
        ;

        /**
         * Causes exception, can only read the response body 1 time
         * https://github.com/square/okhttp/issues/1240
         */
        //            LogUtil.log(LogUtil.LogType.REST, response.body().string());

    } catch (IOException e) {
        listener.fail("IOException: " + e.getLocalizedMessage());
        e.printStackTrace();
    }
}

From source file:com.nuvolect.securesuite.webserver.Comm.java

License:Open Source License

public static void sendPostUi(final Context ctx, String url, final Map<String, String> params,
        final CommPostCallbacks cb) {

    String postBody = "";
    String amphersand = "";

    OkHttpClient okHttpClient = WebService.getOkHttpClient();

    for (Map.Entry<String, String> entry : params.entrySet()) {

        postBody += amphersand;/*from www  .jav a2s .c om*/
        postBody += entry.getKey();
        postBody += "=";
        postBody += entry.getValue();
        amphersand = "&";
    }

    Request request = new Request.Builder().url(url).post(RequestBody.create(MEDIA_TYPE_MARKDOWN, postBody))
            .header(CConst.SEC_TOK, CrypServer.getSecTok()).build();

    okHttpClient.newCall(request).enqueue(new Callback() {

        Handler mainHandler = new Handler(ctx.getMainLooper());

        @Override
        public void onFailure(Request request, IOException e) {

            LogUtil.log("okHttpClient.netCall.onFailure");
            LogUtil.logException(LogUtil.LogType.REST, e);
        }

        @Override
        public void onResponse(Response response) throws IOException {

            final String responseStr;
            final boolean success = response.isSuccessful();

            if (success)
                responseStr = response.body().string();
            else
                responseStr = response.message();

            mainHandler.post(new Runnable() {

                @Override
                public void run() {
                    if (!success) {
                        if (cb != null)
                            cb.fail("unexpected code " + responseStr);
                        return;
                    }
                    if (cb != null)
                        cb.success(responseStr);

                }
            });

        }
    });
}

From source file:com.oneops.crawler.OneOpsFacade.java

License:Apache License

public int disableVerify(Environment env, String userName) throws IOException, OneOpsException {

    String envCiJson = getCiJson(env.getId());
    envCiJson = envCiJson.replace("\"verify\":\"default\"", "\"verify\":\"false\"");
    envCiJson = envCiJson.replace("\"verify\":\"true\"", "\"verify\":\"false\"");

    RequestBody body = RequestBody.create(JSON, envCiJson);

    String url = adapterBaseUrl + "/adapter/rest/cm/simple/cis/" + env.getId();
    Request request = new Request.Builder().url(url).addHeader("X-Cms-User", userName)
            .addHeader("Content-Type", "application/json").put(body).build();

    Response response = client.newCall(request).execute();
    String responseBody = response.body().string();
    int responseCode = response.code();
    log.info("OO response body: " + responseBody + ", code: " + responseCode);
    if (!response.isSuccessful()) {
        throw new OneOpsException("Error while disabling verify. Response from OneOps: " + responseBody
                + " ResponseCode : " + responseCode);
    }/*from  w  ww  .  j a va2  s .c o  m*/
    return responseCode;
}

From source file:com.oneops.crawler.OneOpsFacade.java

License:Apache License

public String getCiJson(long ciId) throws IOException {
    String url = adapterBaseUrl + "/adapter/rest/cm/simple/cis/" + ciId;

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

    Response response = client.newCall(request).execute();
    String responseBody = response.body().string();
    int responseCode = response.code();
    if (!response.isSuccessful()) {
        throw new RuntimeException("Error in getCi api. Response from OneOps: " + responseBody
                + " ResponseCode : " + responseCode);
    }/*from   w  ww  .ja  v  a 2  s.  com*/
    return responseBody;
}

From source file:com.pddstudio.earthview.sync.SynchronizedTask.java

License:Apache License

public final EarthWallpaper[] execute() {

    for (int i = 0; i < earthWallpaperCount; i++) {

        String requestUrl = ApiUtils.getApiUrl(randomRequests ? IdUtils.getRandomId() : earthWallIds[i]);
        try {//  w  w w.  j  a v  a  2 s  . c om
            Request request = new Request.Builder().url(requestUrl).build();
            Response response = okHttpClient.newCall(request).execute();
            if (!response.isSuccessful()) {
                results[i] = null;
                continue;
            }
            EarthWallpaper wallpaper = gson.fromJson(response.body().charStream(), EarthWallpaper.class);
            results[i] = wallpaper;
        } catch (IOException io) {
            /* Ignore the exception which is thrown by OkHttp */}

    }

    return results;
}

From source file:com.piusvelte.okoauth.Helper.java

License:Apache License

@NonNull
public void getTokenSecret(@NonNull OkHttpClient client) {
    Request request = new RequestTokenRequestBuilder(mConsumerKey, mConsumerSecret, mCallbackUrl)
            .url(mTokenRequestUrl).build();
    Response response;

    try {/*  w  ww .j  a v  a2s .  c o m*/
        response = client.newCall(request).execute();

        if (response.isSuccessful() && response.body() != null) {
            String content = response.body().string();

            if (!TextUtils.isEmpty(content)) {
                String[] keyValuePairs = content.split("&");

                if (keyValuePairs.length > 1) {
                    for (String keyValuePair : keyValuePairs) {
                        String[] keyValuePairParts = keyValuePair.split("=");

                        if (keyValuePairParts.length > 1) {
                            String key = keyValuePairParts[0];
                            String value = keyValuePairParts[1];

                            if (RequestBuilder.OAuthParameter.oauth_token.name().equals(key)) {
                                mToken = value;
                            } else if ("oauth_token_secret".equals(key)) {
                                mTokenSecret = value;
                            } else if ("oauth_callback_confirmed".equals(key)) {
                                mIsOAuth10a = Boolean.TRUE.toString().equals(value);
                            }
                        }
                    }
                }
            }
        } else {
            if (BuildConfig.DEBUG) {
                Log.e(TAG, "unsuccessful getting token" + response.toString());
            }
        }
    } catch (IOException e) {
        if (BuildConfig.DEBUG) {
            Log.e(TAG, "failed getting token", e);
        }
    }
}

From source file:com.piusvelte.okoauth.Helper.java

License:Apache License

public boolean getAccessToken(@NonNull OkHttpClient client, @NonNull String authenticatedUrl) {
    if (!TextUtils.isEmpty(authenticatedUrl)) {
        String verifier = getParamValue(authenticatedUrl, "oauth_verifier");

        if (!TextUtils.isEmpty(verifier)) {
            Request request = new AccessTokenRequestBuilder(mConsumerKey, mConsumerSecret, mToken, mTokenSecret,
                    mIsOAuth10a ? verifier : null).url(mAccessTokenUrl).build();
            Response response;

            try {
                response = client.newCall(request).execute();

                if (response.isSuccessful() && response.body() != null) {
                    String content = response.body().string();

                    if (!TextUtils.isEmpty(content)) {
                        String[] keyValuePairs = content.split("&");

                        if (keyValuePairs.length > 1) {
                            for (String keyValuePair : keyValuePairs) {
                                String[] keyValuePairParts = keyValuePair.split("=");

                                if (keyValuePairParts.length > 1) {
                                    String key = keyValuePairParts[0];
                                    String value = keyValuePairParts[1];

                                    if (RequestBuilder.OAuthParameter.oauth_token.name().equals(key)) {
                                        mToken = value;
                                    } else if ("oauth_token_secret".equals(key)) {
                                        mTokenSecret = value;
                                    }//from w  w  w .  jav  a  2  s. c  o m
                                }
                            }

                            return true;// TODO actually check mToken and mTokenSecret
                        }
                    }
                }
            } catch (IOException e) {
                if (BuildConfig.DEBUG) {
                    Log.e(TAG, "failed getting access token", e);
                }
            }
        }
    }

    return false;
}