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.liferay.mobile.screens.viewsets.defaultviews.webcontent.display.WebContentDisplayView.java

License:Open Source License

public WebViewClient getWebViewClientWithCustomHeader() {
    return new WebViewClient() {

        @Override//from www . jav a2 s.c o m
        public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
            return getResource(url.trim());
        }

        @Override
        @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
        public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {

            return getResource(request.getUrl().toString());
        }

        private WebResourceResponse getResource(String url) {
            try {
                OkHttpClient httpClient = LiferayServerContext.getOkHttpClientNoCache();
                com.squareup.okhttp.Request.Builder builder = new com.squareup.okhttp.Request.Builder()
                        .url(url);

                Request request = builder.build();
                com.squareup.okhttp.Response response = httpClient.newCall(request).execute();

                return new WebResourceResponse(
                        response.header("content-type", response.body().contentType().type()),
                        response.header("content-encoding", "utf-8"), response.body().byteStream());
            } catch (Exception e) {
                return null;
            }
        }
    };
}

From source file:com.liferay.mobile.sdk.auth.CookieSignIn.java

License:Open Source License

protected static Callback getCallback(final CookieCallback callback, final CookieManager cookieManager) {

    return new Callback() {

        @Override/*from ww  w .j a va2s.co  m*/
        public void onFailure(Request request, IOException ioe) {
            callback.onFailure(ioe);
        }

        @Override
        public void onResponse(Response response) throws IOException {
            String body = response.body().string();

            Integer position = body.indexOf(AUTH_TOKEN) + AUTH_TOKEN.length();

            String authToken = body.substring(position, position + TOKEN_LENGTH);

            String cookieHeader = getHttpCookies(cookieManager.getCookieStore());

            if (Validator.isNotNull(cookieHeader)) {
                CookieAuthentication auth = new CookieAuthentication(authToken, cookieHeader);

                callback.onSuccess(auth);
            } else {
                callback.onFailure(new AuthenticationException("Cookie invalid or empty"));
            }
        }

    };
}

From source file:com.liferay.mobile.sdk.SDKBuilder.java

License:Open Source License

public Discovery discover(String url, String context, int portalVersion) throws Exception {

    if ("portal".equals(context)) {
        context = "";
    }/*from   w  w  w.  j a v  a  2  s .  c o m*/

    if (portalVersion == 62) {
        if (Validator.isNotNull(context)) {
            context = "/" + context;
        }

        url = String.format("%s%s/api/jsonws?discover", url, context);
    } else if (portalVersion == 7) {
        url = String.format("%s/api/jsonws?discover&contextName=%s", url, context);
    }

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

    if (!response.isSuccessful()) {
        throw new IOException("Unexpected HTTP response: " + response);
    }

    if (portalVersion == 7) {
        JSONParser.registerTypeAdapter(Discovery.class, new DiscoveryDeserializer());

        JSONParser.registerTypeAdapter(Action.class, new ActionDeserializer());
    }

    return JSONParser.fromJSON(response.body().string(), Discovery.class);
}

From source file:com.liuguangqiang.asyncokhttp.RequestTask.java

License:Apache License

public void execute() {
    try {/*  w  w w.  j av a  2  s  . c  o  m*/
        Response response = mClient.newCall(mRequest).execute();
        mResponseHandler.sendStart();
        int code = response.code();
        String responseString = "without response body";
        if (response.body() != null)
            responseString = response.body().string();

        if (response.isSuccessful())
            mResponseHandler.sendSuccess(code, responseString);
        else
            mResponseHandler.sendFailure(code, responseString);
    } catch (IOException e) {
        String error = "unknown";
        if (e.getMessage() != null)
            error = e.getMessage();

        if (error.equals("Canceled"))
            mResponseHandler.sendCancel();
        else
            mResponseHandler.sendFailure(0, error);
    }
}

From source file:com.liulishuo.filedownloader.services.FileDownloadRunnable.java

License:Apache License

@Override
public void run() {
    isPending = false;//from w  w w.ja va  2 s . com
    isRunning = true;
    int retryingTimes = 0;
    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);

    FileDownloadModel model = this.downloadModel;

    if (model == null) {
        FileDownloadLog.e(this, "start runnable but model == null?? %s", getId());

        this.downloadModel = helper.find(getId());

        if (this.downloadModel == null) {
            FileDownloadLog.e(this, "start runnable but downloadMode == null?? %s", getId());
            return;
        }

        model = this.downloadModel;
    }

    if (model.getStatus() != FileDownloadStatus.pending) {
        FileDownloadLog.e(this, "start runnable but status err %s", model.getStatus());
        // ??urlpath(????) ??
        onError(new RuntimeException(String.format("start runnable but status err %s", model.getStatus())));

        return;
    }

    // 
    do {

        long soFar = 0;
        try {

            if (model.isCanceled()) {
                FileDownloadLog.d(this, "already canceled %d %d", model.getId(), model.getStatus());
                break;
            }

            FileDownloadLog.d(FileDownloadRunnable.class, "start download %s %s", getId(), model.getUrl());

            checkIsContinueAvailable();

            Request.Builder headerBuilder = new Request.Builder().url(url);
            addHeader(headerBuilder);
            headerBuilder.tag(this.getId());
            // ?cache?REST?
            headerBuilder.cacheControl(CacheControl.FORCE_NETWORK);

            Call call = client.newCall(headerBuilder.get().build());

            Response response = call.execute();

            final boolean isSucceedStart = response.code() == 200;
            final boolean isSucceedContinue = response.code() == 206 && isContinueDownloadAvailable;

            if (isSucceedStart || isSucceedContinue) {
                long total = downloadTransfer.getTotalBytes();
                if (isSucceedStart || total == 0) {
                    total = response.body().contentLength();
                }

                if (isSucceedContinue) {
                    soFar = downloadTransfer.getSoFarBytes();
                    FileDownloadLog.d(this, "add range %d %d", downloadTransfer.getSoFarBytes(),
                            downloadTransfer.getTotalBytes());
                }

                InputStream inputStream = null;
                RandomAccessFile accessFile = getRandomAccessFile(isSucceedContinue);
                try {
                    inputStream = response.body().byteStream();
                    byte[] buff = new byte[BUFFER_SIZE];
                    maxNotifyBytes = maxNotifyCounts <= 0 ? -1 : total / maxNotifyCounts;

                    updateHeader(response);
                    onConnected(isSucceedContinue, soFar, total);

                    do {
                        int byteCount = inputStream.read(buff);
                        if (byteCount == -1) {
                            break;
                        }

                        accessFile.write(buff, 0, byteCount);

                        //write buff
                        soFar += byteCount;
                        if (accessFile.length() < soFar) {
                            // ??
                            throw new RuntimeException(
                                    String.format("file be changed by others when downloading %d %d",
                                            accessFile.length(), soFar));
                        } else {
                            onProcess(soFar, total);
                        }

                        if (isCancelled()) {
                            onPause();
                            return;
                        }

                    } while (true);

                    if (soFar == total) {
                        onComplete(total);

                        // ?
                        break;
                    } else {
                        throw new RuntimeException(
                                String.format("sofar[%d] not equal total[%d]", soFar, total));
                    }
                } finally {
                    if (inputStream != null) {
                        inputStream.close();
                    }

                    if (accessFile != null) {
                        accessFile.close();
                    }
                }

            } else {
                throw new RuntimeException(String.format("response code error: %d", response.code()));
            }

        } catch (Throwable ex) {
            // TODO ???????
            if (autoRetryTimes > retryingTimes++) {
                // retry
                onRetry(ex, retryingTimes, soFar);
                continue;
            } else {
                // error
                onError(ex);
                break;
            }
        } finally {
            isRunning = false;
        }

    } while (true);

}

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

License:Apache License

private void renewAppToken(final AtomicReference<String> refreshedToken) {
    // Clean up existing token
    ModuleManager.onAppLogout(MaxCore.getConfig().getClientId());

    String authHeader = AuthUtil.generateBasicAuthToken(MaxCore.getConfig().getClientId(),
            MaxCore.getConfig().getClientSecret());
    final CountDownLatch latch = new CountDownLatch(1);
    getApplicationService()/*from   ww  w .  j av a2s .  c  o  m*/
            .appCheckin(Device.getCurrentDeviceId(), authHeader, new Callback<AppLoginResponse>() {
                @Override
                public void onResponse(retrofit.Response<AppLoginResponse> response) {
                    if (response.isSuccess()) {
                        Log.i(TAG, "appCheckin success : ");
                    } else {
                        handleError(response.message());
                        return;
                    }
                    AppLoginResponse appCheckinResponse = response.body();
                    refreshedToken.set(appCheckinResponse.getAccessToken());
                    ModuleManager.onAppLogin(MaxCore.getConfig().getClientId(),
                            new ApplicationToken(appCheckinResponse.getExpiresIn(),
                                    appCheckinResponse.getAccessToken(), appCheckinResponse.getTokenType(),
                                    appCheckinResponse.getScope(), appCheckinResponse.getMmxAppId()),
                            appCheckinResponse.getServerConfig());

                    latch.countDown();
                }

                @Override
                public void onFailure(Throwable throwable) {
                    handleError(throwable.getMessage());
                    latch.countDown();
                }

                private void handleError(String errorMessage) {
                    Log.e(TAG, "appCheckin failed due to : " + errorMessage);
                    ModuleManager.onAppTokenInvalid();
                }
            }).executeInBackground();

    try {
        latch.await(REFRESH_TOKEN_TIMEOUT, TimeUnit.SECONDS);
    } catch (InterruptedException e) {
        Log.d(TAG, "refresh app token timeout");
    }
}

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. j a  v a2s.  c o m*/
                    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 w  ww . j  a  v a2 s . c o 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.qos.internal.CacheManager.java

License:Apache License

public Response cacheResponse(Request request, Response response, CacheOptions options) {
    String requestHash = CacheUtils.getRequestHash(request);
    ResponseCacheEntity operation = findLatestCache(requestHash, request, options);
    long currentTimestamp = System.currentTimeMillis();
    if (null == operation) {
        operation = new ResponseCacheEntity();
        operation.createdAt = currentTimestamp;
        operation.url = request.urlString();
        operation.httpMethod = request.method();
        operation.requestHash = requestHash;
        operation.response = new CachedResponse(response);
        operation.responseCode = response.code();
        operation.isOfflineCache = options.isAlwaysUseCacheIfOffline();

        Log.d(TAG, "Adding cache for request " + request);
    } else {/*from w w w  . ja v a 2  s  .c o m*/
        //Update body
        operation.response = new CachedResponse(response);
        Log.d(TAG, "Updating cache for request " + request);
    }
    operation.updatedAt = currentTimestamp;
    long newExpiredTime = 0;
    if (options.getMaxCacheAge() > 0) {
        newExpiredTime = currentTimestamp + options.getMaxCacheAge() * 1000;
    }
    if (null == operation.getExpiredAt() || newExpiredTime > operation.getExpiredAt()) {
        operation.expiredAt = newExpiredTime;
    }
    operation.save();

    if (null != response.body()) {
        return response.newBuilder()
                .body(ResponseBody.create(response.body().contentType(), operation.response.body)).build();
    } else {
        return response;
    }
}

From source file:com.mallorcasoftware.openweatherclient.api.DefaultApi.java

License:Apache License

private com.squareup.okhttp.Call getCurrentWeatherDataCall(String q, String id, String units, String lang,
        final ProgressResponseBody.ProgressListener progressListener,
        final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
    Object localVarPostBody = null;

    // create path and map variables
    String localVarPath = "/weather".replaceAll("\\{format\\}", "json");

    List<Pair> localVarQueryParams = new ArrayList<Pair>();
    if (q != null)
        localVarQueryParams.addAll(apiClient.parameterToPairs("", "q", q));
    if (id != null)
        localVarQueryParams.addAll(apiClient.parameterToPairs("", "id", id));
    if (units != null)
        localVarQueryParams.addAll(apiClient.parameterToPairs("", "units", units));
    if (lang != null)
        localVarQueryParams.addAll(apiClient.parameterToPairs("", "lang", lang));

    Map<String, String> localVarHeaderParams = new HashMap<String, String>();

    Map<String, Object> localVarFormParams = new HashMap<String, Object>();

    final String[] localVarAccepts = { "application/json" };
    final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts);
    if (localVarAccept != null)
        localVarHeaderParams.put("Accept", localVarAccept);

    final String[] localVarContentTypes = { "application/json" };
    final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes);
    localVarHeaderParams.put("Content-Type", localVarContentType);

    if (progressListener != null) {
        apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() {
            @Override/* w  w  w  .jav  a2  s  .  c o  m*/
            public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain)
                    throws IOException {
                com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request());
                return originalResponse.newBuilder()
                        .body(new ProgressResponseBody(originalResponse.body(), progressListener)).build();
            }
        });
    }

    String[] localVarAuthNames = new String[] { "UserSecurity" };
    return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams,
            localVarFormParams, localVarAuthNames, progressRequestListener);
}