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:com.microsoft.rest.retry.ExponentialBackoffRetryStrategy.java

License:Open Source License

/**
 * Returns if a request should be retried based on the retry count, current response,
 * and the current strategy.//from ww  w  . j a va2 s.  c o  m
 *
 * @param retryCount The current retry attempt count.
 * @param response The exception that caused the retry conditions to occur.
 * @return true if the request should be retried; false otherwise.
 */
@Override
public boolean shouldRetry(int retryCount, Response response) {
    int code = response.code();
    //CHECKSTYLE IGNORE MagicNumber FOR NEXT 2 LINES
    return retryCount < this.retryCount && (code == 408 || (code >= 500 && code != 501 && code != 505));
}

From source file:com.microsoft.rest.RetryHandlerTests.java

License:Open Source License

@Test
public void exponentialRetryEndOn501() throws Exception {
    ServiceClient serviceClient = new ServiceClient() {
    };/*from   w  ww.  ja  v  a  2 s. co  m*/
    serviceClient.getClientInterceptors().add(new Interceptor() {
        // Send 408, 500, 502, all retried, with a 501 ending
        private int[] codes = new int[] { 408, 500, 502, 501 };
        private int count = 0;

        @Override
        public Response intercept(Chain chain) throws IOException {
            return new Response.Builder().request(chain.request()).code(codes[count++])
                    .protocol(Protocol.HTTP_1_1).build();
        }
    });
    Response response = serviceClient.client
            .newCall(new Request.Builder().url("http://localhost").get().build()).execute();
    Assert.assertEquals(501, response.code());
}

From source file:com.microsoft.rest.RetryHandlerTests.java

License:Open Source License

@Test
public void exponentialRetryMax() throws Exception {
    ServiceClient serviceClient = new ServiceClient() {
    };/*from w  w  w  .j  a  v  a  2 s .  c  om*/
    serviceClient.getClientInterceptors().add(new Interceptor() {
        // Send 500 until max retry is hit
        private int count = 0;

        @Override
        public Response intercept(Chain chain) throws IOException {
            Assert.assertTrue(count++ < 5);
            return new Response.Builder().request(chain.request()).code(500).protocol(Protocol.HTTP_1_1)
                    .build();
        }
    });
    Response response = serviceClient.client
            .newCall(new Request.Builder().url("http://localhost").get().build()).execute();
    Assert.assertEquals(500, response.code());
}

From source file:com.microsoft.windowsazure.mobileservices.zumoe2etestapp.MainActivity.java

License:Open Source License

private boolean IsNetBackend() {
    try {/*w ww .j av a2  s  .  c om*/
        OkHttpClient httpclient = new OkHttpClient();

        Request request = new Request.Builder().url(getMobileServiceURL() + "api/runtimeinfo")
                .addHeader("ZUMO-API-VERSION", "2.0.0").build();

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

        String runtimeType;

        if (response.code() == 200) {
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            String responseString = response.body().string();

            JsonObject jsonResult = new JsonParser().parse(responseString).getAsJsonObject();

            runtimeType = jsonResult.get("runtime").getAsJsonObject().get("type").getAsString();

            out.close();
        } else {
            response.body().close();
            throw new IOException(String.valueOf(response.code()));
        }

        if (runtimeType.equals(".NET")) {
            return true;
        }

        return false;
    } catch (Exception ex) {
        return false;
    }
}

From source file:com.miz.functions.MizLib.java

License:Apache License

public static JSONObject getJSONObject(Context context, String url) {
    final OkHttpClient client = MizuuApplication.getOkHttpClient();

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

    try {/*  w ww  . j  ava  2s .  c  o  m*/
        Response response = client.newCall(request).execute();

        if (response.code() >= 429) {
            // HTTP error 429 and above means that we've exceeded the query limit
            // for TMDb. Sleep for 5 seconds and try again.
            Thread.sleep(5000);
            response = client.newCall(request).execute();
        }
        return new JSONObject(response.body().string());
    } catch (Exception e) { // IOException and JSONException
        return new JSONObject();
    }
}

From source file:com.moesif.android.okhttp2.MoesifOkHttp2Stack.java

License:Open Source 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);
    client.networkInterceptors().add(new MoesifOkHttp2Interceptor());

    com.squareup.okhttp.Request.Builder okHttpRequestBuilder = new com.squareup.okhttp.Request.Builder();
    okHttpRequestBuilder.url(request.getUrl());

    Map<String, String> headers = request.getHeaders();
    for (final String name : headers.keySet()) {
        okHttpRequestBuilder.addHeader(name, headers.get(name));
    }/*  ww  w .  j  a  v  a2  s. c  o 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:com.mycelium.lt.api.LtApiClient.java

License:Apache License

private Response getConnectionAndSendRequest(LtRequest request, int timeout) {
    int originalConnectionIndex = _serverEndpoints.getCurrentEndpointIndex();

    // Figure what our current endpoint is. On errors we fail over until we
    // are back at the initial endpoint
    HttpEndpoint initialEndpoint = getEndpoint();
    while (true) {
        HttpEndpoint serverEndpoint = _serverEndpoints.getCurrentEndpoint();
        try {// www  . jav  a 2s .  co  m
            OkHttpClient client = serverEndpoint.getClient();
            _logger.logInfo("LT connecting to " + serverEndpoint.getBaseUrl() + " ("
                    + _serverEndpoints.getCurrentEndpointIndex() + ")");

            // configure TimeOuts
            client.setConnectTimeout(timeout, TimeUnit.MILLISECONDS);
            client.setReadTimeout(timeout, TimeUnit.MILLISECONDS);
            client.setWriteTimeout(timeout, TimeUnit.MILLISECONDS);

            Stopwatch callDuration = Stopwatch.createStarted();
            // build request
            final String toSend = getPostBody(request);
            Request rq = new Request.Builder()
                    .post(RequestBody.create(MediaType.parse("application/json"), toSend))
                    .url(serverEndpoint.getUri(request.toString()).toString()).build();

            // execute request
            Response response = client.newCall(rq).execute();
            callDuration.stop();
            _logger.logInfo(String.format("LtApi %s finished (%dms)", request.toString(),
                    callDuration.elapsed(TimeUnit.MILLISECONDS)));

            // Check for status code 2XX
            if (response.isSuccessful()) {
                if (serverEndpoint instanceof FeedbackEndpoint) {
                    ((FeedbackEndpoint) serverEndpoint).onSuccess();
                }
                return response;
            } else {
                // If the status code is not 200 we cycle to the next server
                logError(String.format("Local Trader server request for class %s returned HTTP status code %d",
                        request.getClass().toString(), response.code()));
            }

        } catch (IOException e) {
            logError("getConnectionAndSendRequest failed IO exception.");
            if (serverEndpoint instanceof FeedbackEndpoint) {
                _logger.logInfo("Resetting tor");
                ((FeedbackEndpoint) serverEndpoint).onError();
            }
        }

        // We had an IO exception or a bad status, fail over and try again
        _serverEndpoints.switchToNextEndpoint();
        // Check if we are back at the initial endpoint, in which case we have
        // to give up
        if (_serverEndpoints.getCurrentEndpointIndex() == originalConnectionIndex) {
            // We have tried all URLs
            return null;
        }
    }
}

From source file:com.mycelium.wapi.api.WapiClient.java

License:Apache License

/**
 * Attempt to connect and send to a URL in our list of URLS, if it fails try
 * the next until we have cycled through all URLs. timeout.
 *//*from   w w  w  . j  a  va 2 s  . c om*/
private Response getConnectionAndSendRequestWithTimeout(Object request, String function, int timeout) {
    int originalConnectionIndex = _serverEndpoints.getCurrentEndpointIndex();
    while (true) {
        // currently active server-endpoint
        HttpEndpoint serverEndpoint = _serverEndpoints.getCurrentEndpoint();
        try {
            OkHttpClient client = serverEndpoint.getClient();
            _logger.logInfo("Connecting to " + serverEndpoint.getBaseUrl() + " ("
                    + _serverEndpoints.getCurrentEndpointIndex() + ")");

            // configure TimeOuts
            client.setConnectTimeout(timeout, TimeUnit.MILLISECONDS);
            client.setReadTimeout(timeout, TimeUnit.MILLISECONDS);
            client.setWriteTimeout(timeout, TimeUnit.MILLISECONDS);

            Stopwatch callDuration = Stopwatch.createStarted();
            // build request
            final String toSend = getPostBody(request);
            Request rq = new Request.Builder().addHeader(MYCELIUM_VERSION_HEADER, versionCode)
                    .post(RequestBody.create(MediaType.parse("application/json"), toSend))
                    .url(serverEndpoint.getUri(WapiConst.WAPI_BASE_PATH, function).toString()).build();

            // execute request
            Response response = client.newCall(rq).execute();
            callDuration.stop();
            _logger.logInfo(String.format("Wapi %s finished (%dms)", function,
                    callDuration.elapsed(TimeUnit.MILLISECONDS)));

            // Check for status code 2XX
            if (response.isSuccessful()) {
                if (serverEndpoint instanceof FeedbackEndpoint) {
                    ((FeedbackEndpoint) serverEndpoint).onSuccess();
                }
                return response;
            } else {
                // If the status code is not 200 we cycle to the next server
                logError(String.format("Http call to %s failed with %d %s", function, response.code(),
                        response.message()));
                // throw...
            }
        } catch (IOException e) {
            logError("IOException when sending request " + function, e);
            if (serverEndpoint instanceof FeedbackEndpoint) {
                _logger.logInfo("Resetting tor");
                ((FeedbackEndpoint) serverEndpoint).onError();
            }
        }
        // Try the next server
        _serverEndpoints.switchToNextEndpoint();
        if (_serverEndpoints.getCurrentEndpointIndex() == originalConnectionIndex) {
            // We have tried all URLs
            return null;
        }

    }
}

From source file:com.nabilhachicha.kc.utils.ConnectionUtils.java

License:Apache License

/**
 * http://www.chromium.org/chromium-os/chromiumos-design-docs/network-portal-detection
 * DNS based detection techniques do not work at all hotspots. The one sure
 * way to check a walled garden is to see if a URL fetch on a known address
 * fetches the data we expect//from ww  w  .j  av a  2s .c o m
 */
public boolean isConnected() {
    try {
        Response response = okHttpClient.newCall(request).execute();
        return HttpStatus.SC_NO_CONTENT == response.code();
    } catch (IOException e) {
        //QLog.w("isConnected error", e);
        return false;
    }
}

From source file:com.navercorp.pinpoint.plugin.okhttp.interceptor.HttpEngineReadResponseMethodInterceptor.java

License:Apache License

@Override
public void after(Object target, Object[] args, Object result, Throwable throwable) {
    if (isDebug) {
        logger.afterInterceptor(target, args);
    }/*w ww .  ja  v  a2s. c  o  m*/

    final Trace trace = traceContext.currentTraceObject();
    if (trace == null) {
        return;
    }

    if (!validate(target)) {
        return;
    }

    try {
        SpanEventRecorder recorder = trace.currentSpanEventRecorder();
        recorder.recordApi(methodDescriptor);
        recorder.recordException(throwable);

        if (statusCode) {
            // type check validate();
            Response response = ((UserResponseGetter) target)._$PINPOINT$_getUserResponse();
            if (response != null) {
                recorder.recordAttribute(AnnotationKey.HTTP_STATUS_CODE, response.code());
            }
        }
    } finally {
        trace.traceBlockEnd();
    }
}