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.anony.okhttp.sample.PostMultipart.java

License:Apache License

public void run() throws Exception {
    // Use the imgur image upload API as documented at https://api.imgur.com/endpoints/image
    RequestBody requestBody = new MultipartBuilder().type(MultipartBuilder.FORM)
            .addFormDataPart("title", "Square Logo").addFormDataPart("image", null,
                    RequestBody.create(MEDIA_TYPE_PNG, new File("website/static/logo-square.png")))
            .build();/*from  w ww  .  j a v a  2 s . c o  m*/

    Request request = new Request.Builder().header("Authorization", "Client-ID " + IMGUR_CLIENT_ID)
            .url("https://api.imgur.com/3/image").post(requestBody).build();

    Response response = client.newCall(request).execute();
    if (!response.isSuccessful())
        throw new IOException("Unexpected code " + response);

    System.out.println(response.body().string());
}

From source file:com.anony.okhttp.sample.PostStreaming.java

License:Apache License

public void run() throws Exception {
    RequestBody requestBody = new RequestBody() {
        @Override/*from w  ww. j a  v  a 2  s. c om*/
        public MediaType contentType() {
            return MEDIA_TYPE_MARKDOWN;
        }

        @Override
        public void writeTo(BufferedSink sink) throws IOException {
            sink.writeUtf8("Numbers\n");
            sink.writeUtf8("-------\n");
            for (int i = 2; i <= 997; i++) {
                sink.writeUtf8(String.format(" * %s = %s\n", i, factor(i)));
            }
        }

        private String factor(int n) {
            for (int i = 2; i < n; i++) {
                int x = n / i;
                if (x * i == n)
                    return factor(x) + "  " + i;
            }
            return Integer.toString(n);
        }
    };

    Request request = new Request.Builder().url("https://api.github.com/markdown/raw").post(requestBody)
            .build();

    Response response = client.newCall(request).execute();
    if (!response.isSuccessful())
        throw new IOException("Unexpected code " + response);

    System.out.println(response.body().string());
}

From source file:com.anony.okhttp.sample.PostString.java

License:Apache License

public void run() throws Exception {
    String postBody = "" + "Releases\n" + "--------\n" + "\n" + " * _1.0_ May 6, 2013\n"
            + " * _1.1_ June 15, 2013\n" + " * _1.2_ August 11, 2013\n";

    Request request = new Request.Builder().url("https://api.github.com/markdown/raw")
            .post(RequestBody.create(MEDIA_TYPE_MARKDOWN, postBody)).build();

    Response response = client.newCall(request).execute();
    if (!response.isSuccessful())
        throw new IOException("Unexpected code " + response);

    System.out.println(response.body().string());
}

From source file:com.anony.okhttp.sample.Progress.java

License:Apache License

public void run() throws Exception {
    Request request = new Request.Builder().url("https://publicobject.com/helloworld.txt").build();

    final ProgressListener progressListener = new ProgressListener() {
        @Override// w w w. jav a 2 s  .c o m
        public void update(long bytesRead, long contentLength, boolean done) {
            System.out.println(bytesRead);
            System.out.println(contentLength);
            System.out.println(done);
            System.out.format("%d%% done\n", (100 * bytesRead) / contentLength);
        }
    };

    client.networkInterceptors().add(new Interceptor() {
        @Override
        public Response intercept(Chain chain) throws IOException {
            Response originalResponse = chain.proceed(chain.request());
            return originalResponse.newBuilder()
                    .body(new ProgressResponseBody(originalResponse.body(), progressListener)).build();
        }
    });

    Response response = client.newCall(request).execute();
    if (!response.isSuccessful())
        throw new IOException("Unexpected code " + response);

    System.out.println(response.body().string());
}

From source file:com.anony.okhttp.sample.RequestBodyCompression.java

License:Apache License

public void run() throws Exception {
    Map<String, String> requestBody = new LinkedHashMap<>();
    requestBody.put("longUrl", "https://publicobject.com/2014/12/04/html-formatting-javadocs/");
    RequestBody jsonRequestBody = RequestBody.create(MEDIA_TYPE_JSON, new Gson().toJson(requestBody));
    Request request = new Request.Builder()
            .url("https://www.googleapis.com/urlshortener/v1/url?key=" + GOOGLE_API_KEY).post(jsonRequestBody)
            .build();//from   ww w .  j a  v a  2s .c o  m

    Response response = client.newCall(request).execute();
    if (!response.isSuccessful())
        throw new IOException("Unexpected code " + response);

    System.out.println(response.body().string());
}

From source file:com.anony.okhttp.sample.RewriteResponseCacheControl.java

License:Apache License

public void run() throws Exception {
    for (int i = 0; i < 5; i++) {
        System.out.println("    Request: " + i);

        Request request = new Request.Builder().url("https://api.github.com/search/repositories?q=http")
                .build();//  ww w . j  a v  a 2s.  com

        if (i == 2) {
            // Force this request's response to be written to the cache. This way, subsequent responses
            // can be read from the cache.
            System.out.println("Force cache: true");
            client.networkInterceptors().add(REWRITE_CACHE_CONTROL_INTERCEPTOR);
        } else {
            System.out.println("Force cache: false");
            client.networkInterceptors().clear();
        }

        Response response = client.newCall(request).execute();
        response.body().close();
        if (!response.isSuccessful())
            throw new IOException("Unexpected code " + response);

        System.out.println("    Network: " + (response.networkResponse() != null));
        System.out.println();
    }
}

From source file:com.appstarter.utils.WebUtils.java

License:Apache License

public static String doHttpGet(String url) throws AppStarterException {
    if (BuildConfig.DEBUG) {
        Log.d(TAG, "doHttpGet - url: " + url);
    }//from  ww w  .ja va2s  .  c  o m

    String ret = "";

    OkHttpClient client = new OkHttpClient();
    client.setConnectTimeout(15, TimeUnit.SECONDS); // connect timeout
    client.setReadTimeout(15, TimeUnit.SECONDS); // socket timeout

    try {
        Request request = new Request.Builder().url(new URL(url))
                //               .header("User-Agent", "OkHttp Headers.java")
                //               .addHeader("Accept", "application/json; q=0.5")
                .build();

        Response response = client.newCall(request).execute();
        if (!response.isSuccessful()) {
            String debugMessage = "doHttpGet - OkHttp.Response is not successful - " + response.message() + " ("
                    + response.code() + ")";
            throw new AppStarterException(AppStarterException.ERROR_SERVER, debugMessage);
        }
        ret = response.body().string();
    } catch (IOException e) {
        throw new AppStarterException(e, AppStarterException.ERROR_NETWORK_GET);
    }

    return ret;
}

From source file:com.appstarter.utils.WebUtils.java

License:Apache License

public static String doHttpPost(String url, List<NameValuePair> params) throws AppStarterException {
    if (BuildConfig.DEBUG) {
        Log.d(TAG, "doHttpPost - url: " + debugRequest(url, params));
    }//from w w w.j  av a  2  s  .  com

    String ret = "";

    OkHttpClient client = new OkHttpClient();
    client.setConnectTimeout(15, TimeUnit.SECONDS); // connect timeout
    client.setReadTimeout(15, TimeUnit.SECONDS); // socket timeout

    FormEncodingBuilder builder = new FormEncodingBuilder();
    for (NameValuePair nvp : params) {
        builder.add(nvp.getName(), nvp.getValue());
    }
    RequestBody formBody = builder.build();

    try {
        Request request = new Request.Builder().url(new URL(url))
                //               .header("User-Agent", "OkHttp Headers.java")
                //               .addHeader("Accept", "application/json; q=0.5")
                .post(formBody).build();

        Response response = client.newCall(request).execute();
        if (!response.isSuccessful()) {
            String debugMessage = "doHttpPost - OkHttp.Response is not successful - " + response.message()
                    + " (" + response.code() + ")";
            throw new AppStarterException(AppStarterException.ERROR_SERVER, debugMessage);
        }
        ret = response.body().string();
    } catch (IOException e) {
        throw new AppStarterException(e, AppStarterException.ERROR_NETWORK_GET);
    }

    return ret;
}

From source file:com.ariadnext.idcheckio.invoker.ApiClient.java

License:Apache License

/**
 * Handle the given response, return the deserialized object when the response is successful.
 *
 * @param <T> Type/* w  w  w.j  a v a 2  s .  c o  m*/
 * @param response Response
 * @param returnType Return type
 * @throws ApiException If the response has a unsuccessful status code or
 *   fail to deserialize the response body
 * @return Type
 */
public <T> T handleResponse(Response response, Type returnType) throws ApiException {
    if (response.isSuccessful() || response.code() == 303) {
        if (returnType == null || response.code() == 204) {
            // returning null if the returnType is not defined,
            // or the status code is 204 (No Content)
            return null;
        } else {
            return deserialize(response, returnType);
        }
    } else {
        String respBody = null;
        if (response.body() != null) {
            try {
                respBody = response.body().string();
            } catch (IOException e) {
                throw new ApiException(response.message(), e, response.code(), response.headers().toMultimap());
            }
        }
        throw new ApiException(response.message(), response.code(), response.headers().toMultimap(), respBody);
    }
}

From source file:com.auth0.api.internal.ApplicationInfoRequest.java

License:Open Source License

@Override
public void onResponse(Response response) throws IOException {
    if (!response.isSuccessful()) {
        String message = "Received app info failed response with code " + response.code() + " and body "
                + response.body().string();
        postOnFailure(new IOException(message));
        return;//from   w  ww . j av a2 s.co  m
    }
    try {
        String json = response.body().string();
        JSONTokener tokenizer = new JSONTokener(json);
        tokenizer.skipPast("Auth0.setClient(");
        if (!tokenizer.more()) {
            postOnFailure(tokenizer.syntaxError("Invalid App Info JSONP"));
            return;
        }
        Object nextValue = tokenizer.nextValue();
        if (!(nextValue instanceof JSONObject)) {
            tokenizer.back();
            postOnFailure(tokenizer.syntaxError("Invalid JSON value of App Info"));
        }
        JSONObject jsonObject = (JSONObject) nextValue;
        Log.d(TAG, "Obtained JSON object from JSONP: " + jsonObject);
        Application app = getReader().readValue(jsonObject.toString());
        postOnSuccess(app);
    } catch (JSONException | IOException e) {
        postOnFailure(new APIClientException("Failed to parse JSONP", e));
    }
}