Example usage for com.squareup.okhttp Response message

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

Introduction

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

Prototype

String message

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

Click Source Link

Usage

From source file:com.magnet.max.android.MaxRestAuthenticator.java

License:Apache License

private void renewUserToken(final AtomicReference<String> refreshedToken) {
    // Trying to auto recover to renew user token
    final UserToken userToken = ModuleManager.getUserToken();
    if (null != userToken && StringUtil.isNotEmpty(userToken.getRefreshToken())) {
        final CountDownLatch latch = new CountDownLatch(1);
        getUserService().renewToken(new RenewTokenRequest(userToken.getRefreshToken()),
                AuthUtil.generateOAuthToken(userToken.getRefreshToken()), new Callback<UserLoginResponse>() {
                    @Override//from w  w  w  .  ja  va  2  s  .  com
                    public void onResponse(retrofit.Response<UserLoginResponse> response) {
                        if (response.isSuccess()) {
                            Log.i(TAG, "renewToken success : ");
                        } else {
                            Log.e(TAG, "renewToken failed due to : " + response.message());
                            handleUserTokenRefreshFailure();
                            latch.countDown();
                            return;
                        }

                        UserLoginResponse userLoginResponse = response.body();

                        if (null != userLoginResponse.getAccessToken()) {
                            ModuleManager.onUserTokenRefresh(userLoginResponse.getUser().getUserIdentifier(),
                                    new UserToken(userLoginResponse.getExpiresIn(),
                                            userLoginResponse.getAccessToken(), userToken.getRefreshToken(),
                                            userLoginResponse.getTokenType()),
                                    null);

                            refreshedToken.set(userLoginResponse.getAccessToken());
                        } else {
                            handleUserTokenRefreshFailure();
                        }

                        latch.countDown();
                    }

                    @Override
                    public void onFailure(Throwable throwable) {
                        Log.e(TAG, "renewToken failed due to : " + throwable.getMessage());
                        handleUserTokenRefreshFailure();
                        latch.countDown();
                    }
                }).executeInBackground();

        try {
            latch.await(REFRESH_TOKEN_TIMEOUT, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            Log.d(TAG, "refresh user token timeout");
        }
    } else {
        Log.w(TAG, "Refresh token is not available, won't renew");
        handleUserTokenRefreshFailure();
    }
}

From source file:com.magnet.max.android.rest.qos.internal.CachedResponse.java

License:Apache License

public CachedResponse(Response response) {
    this.code = response.code();
    this.protocol = response.protocol().toString();
    this.message = response.message();

    parseHeaders(response.headers());//from ww  w.j  a  va  2  s .co  m

    if (null != response.body()) {
        try {
            Buffer buffer = new Buffer();
            response.body().source().readAll(buffer);
            body = CacheUtils.copyBody(buffer);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

From source file:com.magnet.max.android.rest.RequestInterceptor.java

License:Apache License

@Override
public Response intercept(Chain chain) throws IOException {
    Request request = chain.request();
    Log.i(TAG, "---------Intercepting url : " + request.method() + " " + request.urlString());

    CallOptions options = requestManager.popRequestOptions(request);
    boolean isCacheEnabled = null != options && null != options.getCacheOptions();
    if (isCacheEnabled) {
        if (options.getCacheOptions().isAlwaysUseCacheIfOffline() && ConnectivityManager.getInstance()
                .getConnectivityStatus() == ConnectivityManager.TYPE_NOT_CONNECTED) {
            Response cachedResponse = cacheManager.getCachedResponse(request, options.getCacheOptions());
            if (null != cachedResponse) {
                Log.d(TAG, "-------return from cache when isAlwaysUseCacheIfOffline==true and offline");
                return cachedResponse;
            } else {
                throw new IOException("It's offline and no cached response found");
            }/*  w w  w.j  a va2  s .  co  m*/
        } else if (options.getCacheOptions().getMaxCacheAge() > 0) { // Return from cache if it's not expired
            Response cachedResponse = cacheManager.getCachedResponse(request, options.getCacheOptions());
            if (null != cachedResponse) {
                Log.d(TAG, "-------return from cache when maxCacheAge = "
                        + options.getCacheOptions().getMaxCacheAge());
                return cachedResponse;
            }
        }
    }

    //Add auth token for network call
    String token = null;
    if ((authTokenProvider.isAuthEnabled() && authTokenProvider.isAuthRequired(request))
            && (null != authTokenProvider.getAppToken() || null != authTokenProvider.getUserToken())) {
        String existingToken = request.header(AuthUtil.AUTHORIZATION_HEADER);
        if (null != existingToken && existingToken.startsWith("Basic")) {
            // Already has Basic Auth header, don't overwrite
        } else {
            token = getToken();
        }
    }

    boolean useMock = false;
    if (null != options) {
        if (isCacheEnabled) {
            useMock = options.getCacheOptions().useMock();
        } else if (null != options.getReliableCallOptions()) {
            useMock = options.getReliableCallOptions().useMock();
        }
    }

    Response response = null;
    long startTime = System.currentTimeMillis();
    try {
        // Modify request
        if (null != token || useMock) {
            Request.Builder newRequestBuilder = chain.request().newBuilder();

            if (null != token) {
                newRequestBuilder.header(AuthUtil.AUTHORIZATION_HEADER, AuthUtil.generateOAuthToken(token));
            }

            if (useMock) {
                newRequestBuilder.url(request.urlString().replace(RestConstants.REST_BASE_PATH,
                        RestConstants.REST_MOCK_BASE_PATH));
            }

            response = chain.proceed(newRequestBuilder.build());
        } else {
            response = chain.proceed(request);
        }

        if (null != options && options.isReliable()) { // Reliable call
            requestManager.removeReliableRequest(request);
        }
    } catch (IOException e) {
        //if(null != options && options.isReliable()) { // Reliable call
        //  requestManager.saveReliableRequest(request, null, null, options.getReliableCallOptions(), e.getMessage());
        //  //TODO :
        //  return null;  // Swallow exception
        //} else {
        //  throw e;
        //}
        Log.e(TAG, "error when getting response", e);
        throw e;
    }

    Log.d(TAG,
            "---------Response for url : " + request.method() + " " + request.urlString() + " : code = "
                    + response.code() + ", message = " + response.message() + " in "
                    + (System.currentTimeMillis() - startTime) + " ms");

    //Save/Update response in cache
    if (response.isSuccessful() && isCacheEnabled && (options.getCacheOptions().getMaxCacheAge() > 0
            || options.getCacheOptions().isAlwaysUseCacheIfOffline())) {
        return cacheManager.cacheResponse(request, response, options.getCacheOptions());
    }

    return response;
}

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));
    }/*  w ww.  ja  v a  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: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.
 *///w  w w  . j  av a2s  .  c o  m
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.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   w ww. jav a  2s  .  c o m*/
        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.parse.ParseOkHttpClient.java

License:Open Source License

@Override
/* package */ ParseHttpResponse getResponse(Response okHttpResponse) throws IOException {
    // Status code
    int statusCode = okHttpResponse.code();

    // Content/*from   w w w  .  j av a 2s  . com*/
    InputStream content = okHttpResponse.body().byteStream();

    // Total size
    int totalSize = (int) okHttpResponse.body().contentLength();

    // Reason phrase
    String reasonPhrase = okHttpResponse.message();

    // Headers
    Map<String, String> headers = new HashMap<>();
    for (String name : okHttpResponse.headers().names()) {
        headers.put(name, okHttpResponse.header(name));
    }

    // Content type
    String contentType = null;
    ResponseBody body = okHttpResponse.body();
    if (body != null && body.contentType() != null) {
        contentType = body.contentType().toString();
    }

    return new ParseHttpResponse.Builder().setStatusCode(statusCode).setContent(content).setTotalSize(totalSize)
            .setReasonPhrase(reasonPhrase).setHeaders(headers).setContentType(contentType).build();
}

From source file:com.peach.masktime.module.net.OkHttpStack.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();
    LogUtils.i(TAG, "timeoutMs = " + timeoutMs);
    client.setProxy(Proxy.NO_PROXY);
    client.setConnectTimeout(timeoutMs, TimeUnit.MILLISECONDS);
    client.setReadTimeout(timeoutMs, TimeUnit.MILLISECONDS);
    client.setWriteTimeout(timeoutMs, TimeUnit.MILLISECONDS);

    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));
    }/*w w  w  .j av  a  2s. c  om*/
    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.phattn.vnexpressnews.io.OkHttpStack.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);

    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));
    }/*from w  w w .j a va 2s . 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, length = responseHeaders.size(); i < length; i++) {
        final String name = responseHeaders.name(i);
        final String value = responseHeaders.value(i);
        if (name != null) {
            response.addHeader(new BasicHeader(name, value));
        }
    }

    return response;
}

From source file:com.quarterfull.newsAndroid.reader.HttpJsonRequest.java

License:Open Source License

public InputStream PerformJsonRequest(HttpUrl url) throws Exception {
    Request request = new Request.Builder().url(url).get().build();

    //http://nelenkov.blogspot.de/2011/12/using-custom-certificate-trust-store-on.html
    //http://stackoverflow.com/questions/5947162/https-and-self-signed-certificate-issue
    //http://hc.apache.org/httpcomponents-client-ga/tutorial/html/connmgmt.html#d4e537
    //http://stackoverflow.com/questions/859111/how-do-i-accept-a-self-signed-certificate-with-a-java-httpsurlconnection
    //http://developer.android.com/training/articles/security-ssl.html

    // CookieHandler.setDefault(new CookieManager());

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

    if (response.isSuccessful()) {
        return response.body().byteStream();
    } else {/*from   w w w .j  av a  2s .com*/
        throw new Exception(response.message());
    }
}