Example usage for com.squareup.okhttp Response request

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

Introduction

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

Prototype

Request request

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

Click Source Link

Usage

From source file:com.he5ed.lib.cloudprovider.apis.BoxApi.java

License:Apache License

@Override
public synchronized File getThumbnail(@NonNull CFile file) throws RequestFailException {
    if (TextUtils.isEmpty(mAccessToken)) {
        throw new RequestFailException("Access token not available");
    }/*from  w w  w  .j a v  a2s .  c o  m*/

    Uri uri = Uri.parse(API_BASE_URL);
    String url = uri.buildUpon().appendEncodedPath("files/" + file.getId() + "/thumbnail.png")
            .appendQueryParameter("min_height", "100").appendQueryParameter("min_width", "100")
            .appendQueryParameter("max_height", "256").appendQueryParameter("max_width", "256").build()
            .toString();

    Request request = new Request.Builder().url(url)
            .header("Authorization", String.format("Bearer %s", mAccessToken)).get().build();

    try {
        Response response = mHttpClient.newCall(request).execute();
        if (response.isSuccessful()) {
            switch (response.code()) {
            case 200:
                // redirect to url
                return downloadFile(response.request(), file.getId() + ".png");
            case 202:
                // retry after due to file just uploaded
                delayDownloadFile(file, file.getId() + ".png");
                break;
            case 302:
                // redirect to url
                return downloadFile(response.request(), file.getId() + ".png");
            }
        } else {
            throw new RequestFailException(response.message(), response.code());
        }
    } catch (IOException e) {
        e.printStackTrace();
        throw new RequestFailException(e.getMessage());
    }
    return null;
}

From source file:com.he5ed.lib.cloudprovider.apis.OneDriveApi.java

License:Apache License

@Override
public File downloadFile(@NonNull CFile file, String filename) throws RequestFailException {
    if (TextUtils.isEmpty(mAccessToken)) {
        throw new RequestFailException("Access token not available");
    }/*w w  w.ja  v  a 2  s. com*/

    // assign filename
    if (TextUtils.isEmpty(filename))
        filename = file.getName();

    Request request = new Request.Builder().url(API_BASE_URL + "/drive/items/" + file.getId() + "/content")
            .header("Authorization", String.format("Bearer %s", mAccessToken)).get().build();

    try {
        Response response = mHttpClient.newCall(request).execute();
        if (response.isSuccessful()) {
            switch (response.code()) {
            case 200:
                // redirect to url
                return downloadFile(response.request(), filename);
            case 302:
                // redirect to url
                return downloadFile(response.request(), filename);
            }
        } else {
            throw new RequestFailException(response.message(), response.code());
        }
    } catch (IOException e) {
        e.printStackTrace();
        throw new RequestFailException(e.getMessage());
    }
    return null;
}

From source file:com.he5ed.lib.cloudprovider.apis.OneDriveApi.java

License:Apache License

@Override
public File getThumbnail(@NonNull CFile file) throws RequestFailException {
    if (TextUtils.isEmpty(mAccessToken)) {
        throw new RequestFailException("Access token not available");
    }//from  www  .j a  v  a 2s.c o m

    Request request = new Request.Builder()
            .url(API_BASE_URL + "/drive/items/" + file.getId() + "/thumbnails/0/medium/content")
            .header("Authorization", String.format("Bearer %s", mAccessToken)).get().build();

    try {
        Response response = mHttpClient.newCall(request).execute();
        if (response.isSuccessful()) {
            switch (response.code()) {
            case 200:
                // redirect to url
                return downloadFile(response.request(), file.getId() + ".jpg");
            case 302:
                // redirect to url
                return downloadFile(response.request(), file.getId() + ".jpg");
            }
        } else {
            throw new RequestFailException(response.message(), response.code());
        }
    } catch (IOException e) {
        e.printStackTrace();
        throw new RequestFailException(e.getMessage());
    }
    return null;
}

From source file:com.liferay.mobile.android.auth.basic.BasicAuthAutenticator.java

License:Open Source License

@Override
public Request authenticate(Proxy proxy, Response response) throws IOException {

    String credential = Credentials.basic(username, password);
    return response.request().newBuilder().header(Headers.AUTHORIZATION, credential).build();
}

From source file:com.liferay.mobile.android.auth.basic.DigestAuthentication.java

License:Open Source License

@Override
public Request authenticate(Proxy proxy, Response response) throws IOException {

    Request request = response.request();
    Builder builder = request.newBuilder();

    try {/*from w  w w .j  a  v  a2  s  . co m*/
        BasicHeader authenticateHeader = new BasicHeader(Headers.WWW_AUTHENTICATE,
                response.header(Headers.WWW_AUTHENTICATE));

        DigestScheme scheme = new DigestScheme();
        scheme.processChallenge(authenticateHeader);

        BasicHttpRequest basicHttpRequest = new BasicHttpRequest(request.method(), request.uri().getPath());

        UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(username, password);

        String authorizationHeader = scheme.authenticate(credentials, basicHttpRequest).getValue();

        builder.addHeader(Headers.AUTHORIZATION, authorizationHeader);
    } catch (Exception e) {
        throw new IOException(e);
    }

    return builder.build();
}

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

License:Open Source License

@Override
public Request authenticate(Proxy proxy, Response response) throws IOException {

    Request request = response.request();

    Builder builder = request.newBuilder();

    try {//from  www.j av a  2  s. c om
        BasicHeader authenticateHeader = new BasicHeader(Headers.WWW_AUTHENTICATE,
                response.header(Headers.WWW_AUTHENTICATE));

        DigestScheme scheme = new DigestScheme();

        scheme.processChallenge(authenticateHeader);

        BasicHttpRequest basicHttpRequest = new BasicHttpRequest(request.method(), request.uri().getPath());

        UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(username, password);

        String authorizationHeader = scheme.authenticate(credentials, basicHttpRequest).getValue();

        builder.addHeader(Headers.AUTHORIZATION, authorizationHeader);
    } catch (Exception e) {
        throw new IOException(e);
    }

    return builder.build();
}

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

License:Apache License

@Override
public Request authenticate(Proxy proxy, Response response) throws IOException {
    Request request = response.request();
    String originalToken = AuthUtil.extractOAuthToken(request.header(AuthUtil.AUTHORIZATION_HEADER));
    String authError = response.header(Response401.ERROR_HEADER);
    Log.e(TAG, "Got 401 for request : " + request.urlString() + " with token :\n" + originalToken
            + "\n error : " + authError);

    Response401 response401 = null;
    if (StringUtil.isNotEmpty(authError)) {
        response401 = new Response401(authError);
    }//from  w  w  w  . ja  v  a 2 s  .c  om

    final AtomicReference<String> refreshedToken = new AtomicReference<>();

    String requestPath = request.httpUrl().encodedPath();
    if (requestPath.endsWith("/")) {
        requestPath = requestPath.substring(0, requestPath.length() - 1);
    }
    if (requestPath.endsWith(RestConstants.APP_LOGIN_URL)
            || requestPath.endsWith(RestConstants.APP_LOGIN_WITH_DEVICE_URL)) {
        // App login failed, handle by callback in MagnetRestAdapter
    } else if (requestPath.endsWith(RestConstants.USER_LOGIN_URL)
            || requestPath.endsWith(RestConstants.USER_LOGOUT_URL)) {
        // User login failed, handle by callback in User.login
    } else if (requestPath.endsWith(RestConstants.USER_REFRESH_TOKEN_URL)) {
        // User token refresh failed
        MaxCore.userTokenInvalid(originalToken, null);
    } else if (null != response401
            && response401.getErrorType() == Response401.AuthErrorType.CLIENT_ACCESS_TOKEN) {
        renewAppToken(refreshedToken);
    } else if (null != response401
            && response401.getErrorType() == Response401.AuthErrorType.USER_ACCESS_TOKEN) {
        renewUserToken(refreshedToken);
    } else {
        if (null != response401) {
            if (response401.getErrorType() == Response401.AuthErrorType.USER_ACCESS_TOKEN) {
                MaxCore.userTokenInvalid(originalToken, null);
            } else {
                MaxCore.appTokenInvalid(originalToken, null);
            }
        } else {
            MaxCore.tokenInvalid(originalToken, null);
        }
    }

    // Reply the request with refreshed token
    if (null != refreshedToken.get()) {
        Log.d(TAG, "Using refreshed token : " + refreshedToken.get());

        // Replace token
        Headers newHeaders = request.headers().newBuilder()
                .set(AuthUtil.AUTHORIZATION_HEADER, AuthUtil.generateOAuthToken(refreshedToken.get())).build();

        return request.newBuilder().headers(newHeaders).build();
    } else {
        Log.w(TAG, "No new token available, won't answer the challenge for " + request.urlString());
    }

    return null;
}

From source file:com.mvcoding.financius.api.EndpointAuthenticator.java

License:Open Source License

@Override
public Request authenticate(Proxy proxy, Response response) throws IOException {
    String token = session.isLoggedIn() ? session.getToken() : null;
    boolean alreadyHadToken = !Strings.isNullOrEmpty(token);
    if (!alreadyHadToken) {
        token = getNewToken();/*from   w ww. ja v a2 s  .c om*/
    }

    boolean isNoTokenOrAlreadyRetried = Strings.isNullOrEmpty(token)
            || !Strings.isNullOrEmpty(response.request().header("Retry"));
    if (isNoTokenOrAlreadyRetried) {
        return null;
    }

    if (alreadyHadToken) {
        token = getNewToken();
    }

    session.setToken(token);

    return response.request().newBuilder().header("Authorization", session.getTokenForRequest())
            .header("Retry", "true").build();
}

From source file:dulleh.akhyou.Utils.CloudflareHttpClient.java

License:Open Source License

private Response solveCloudflare(Response response) throws IOException, CloudflareException {
    // Cloudflare requires 5 seconds of waiting before posting the response
    try {/*  w w w .  j ava2s .c o  m*/
        Thread.sleep(5000);
    } catch (InterruptedException ignored) {
        // We cannot really do anything meaningful here
    }
    URI url = response.request().uri();
    String domain = url.getHost();

    Document page = Jsoup.parse(response.body().string());
    String challenge = page.select("[name=jschl_vc]").first().attr("value");
    String challengePass = page.select("[name=pass]").first().attr("value");
    String function = transformFunction(page.select("head script").first().html());

    // Get the JS context and set the optimization to -1 (interpreted mode), so that
    // it actually works on Android
    Context context = Context.enter();
    context.setOptimizationLevel(-1);
    try {
        // Get a JS scope so we can execute the Cloudflare code
        Scriptable scope = context.initSafeStandardObjects();
        Object jsResult = context.evaluateString(scope, function, "<cloudflare>", 1, null);
        long answer = new BigDecimal(jsResult.toString()).longValue() + domain.length();
        String submitUrl = String.format("%s://%s/cdn-cgi/l/chk_jschl?pass=%s&jschl_answer=%d&jschl_vc=%s",
                url.getScheme(), domain, challengePass, answer, challenge);

        Request solved = new Request.Builder().url(submitUrl).header("Referer", url.toString()).build();

        return client.newCall(solved).execute();
    } finally {
        Context.exit();
    }
}

From source file:es.bsc.vmmclient.rest.VmmRestClient.java

License:Open Source License

public VmmRestClient(String url, long timeout, final String username, final String password) {
    if (url.startsWith("https://")) {
        // TODO: add the option to accept only Trusted HTTPS connections
        okHttpClient = getUnsafeOkHttpClient();
    } else {/*from  w w  w.  j ava2  s.c o  m*/
        okHttpClient = new OkHttpClient();
    }
    // Define our own okHttpClient to increase the timeout
    okHttpClient.setReadTimeout(timeout, TimeUnit.SECONDS);

    if (username != null && password != null) {
        okHttpClient.setAuthenticator(new Authenticator() {
            @Override
            public Request authenticate(Proxy proxy, Response response) throws IOException {
                String credential = Credentials.basic(username, password);
                return response.request().newBuilder().header("Authorization", credential).build();
            }

            @Override
            public Request authenticateProxy(Proxy proxy, Response response) throws IOException {
                return null;
            }
        });
    }

    RestAdapter restAdapter = new RestAdapter.Builder().setEndpoint(url).setClient(new OkClient(okHttpClient))
            .build();
    service = restAdapter.create(VmmService.class);
}