Example usage for com.squareup.okhttp Callback Callback

List of usage examples for com.squareup.okhttp Callback Callback

Introduction

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

Prototype

Callback

Source Link

Usage

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

License:Apache License

/**
 * Ensure that the access token is still valid
 * Access token can be expired or revoked by user
 * Try to refresh the access token if it is expired
 *//*from w  ww  .  j a  va 2 s  .  com*/
private void validateAccessToken() {
    Request request = getUserInfoRequest(mAccessToken);

    mHttpClient.newCall(request).enqueue(new Callback() {
        @Override
        public void onFailure(Request request, IOException e) {
            e.printStackTrace();
            if (mPrepareListener != null)
                mPrepareListener.onPrepareFail(e);
            Log.e(TAG, e.getMessage());
        }

        @Override
        public void onResponse(Response response) throws IOException {
            if (response.isSuccessful() && response.code() == 200) {
                if (mPrepareListener != null)
                    mPrepareListener.onPrepareSuccessful();
            } else {
                switch (response.code()) {
                case 401:
                    // unauthorized
                    resetAccount();
                    break;
                default:
                    break;
                }
                Log.e(TAG, response.code() + ": " + response.body().string());
            }
        }
    });
}

From source file:com.he5ed.lib.cloudprovider.auth.OAuth2Fragment.java

License:Apache License

/**
 * Get API access token by sending POST request with params build from AuthHelper
 *
 * @param body parameter to be passed with the request
 *//*from   w  ww  .jav  a2s .  c  o m*/
private void getAccessToken(RequestBody body) {
    String url;
    try {
        url = AuthHelper.getAccessTokenUri(mCloudApi).toString();
    } catch (MalformedURLException e) {
        e.printStackTrace();
        // register event to listener
        if (mListener != null)
            mListener.onAuthError(getString(R.string.auth_error_malformed_url));
        return;
    }

    Request request = new Request.Builder().url(url).post(body).build();

    mHttpClient.newCall(request).enqueue(new Callback() {
        @Override
        public void onFailure(Request request, IOException e) {
            // register event to listener
            if (mListener != null)
                mListener.onAuthError(getString(R.string.auth_error_access_token_fail));
        }

        @Override
        public void onResponse(Response response) throws IOException {
            if (response.isSuccessful()) {
                try {
                    JSONObject jsonObject = new JSONObject(response.body().string());
                    mTokenInfo = AuthHelper.extractAccessToken(mCloudApi, jsonObject);
                    if (mTokenInfo != null) {
                        getUserInfo(mTokenInfo.get(Authenticator.KEY_ACCESS_TOKEN));
                    } else {
                        // register event to listener
                        if (mListener != null)
                            mListener.onAuthError(getString(R.string.auth_error_access_token_fail));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    // register event to listener
                    if (mListener != null)
                        mListener.onAuthError(getString(R.string.auth_error_access_token_fail));
                }

            } else {
                // register event to listener
                if (mListener != null)
                    mListener.onAuthError(getString(R.string.auth_error_access_token_fail));
            }
        }
    });

}

From source file:com.he5ed.lib.cloudprovider.auth.OAuth2Fragment.java

License:Apache License

private void getUserInfo(final String accessToken) {

    Request request = AuthHelper.getUserInfoRequest(mCloudApi, accessToken);

    mHttpClient.newCall(request).enqueue(new Callback() {
        @Override//from   w w  w.j a v  a2 s . c o m
        public void onFailure(Request request, IOException e) {
            // register event to listener
            if (mListener != null)
                mListener.onAuthError(getString(R.string.auth_error_user_info_fail));
        }

        @Override
        public void onResponse(Response response) throws IOException {
            if (response.isSuccessful()) {
                try {
                    JSONObject jsonObject = new JSONObject(response.body().string());

                    addAccount(AuthHelper.extractUser(mCloudApi, jsonObject));
                } catch (JSONException e) {
                    e.printStackTrace();
                    // register event to listener
                    if (mListener != null)
                        mListener.onAuthError(getString(R.string.auth_error_user_info_fail));
                }
            } else {
                // register event to listener
                if (mListener != null)
                    mListener.onAuthError(getString(R.string.auth_error_user_info_fail));
            }
        }
    });
}

From source file:com.heroiclabs.sdk.android.HttpClient.java

License:Apache License

/** {@inheritDoc} */
public <T> Deferred<Response<T>> execute(final @NonNull Request<T> request) {
    final Deferred<Response<T>> deferred = new Deferred<>();

    // Select the host, implicitly only allow HTTPS.
    HttpUrl.Builder urlBuilder = new HttpUrl.Builder().scheme("https")
            .host(getServer(request.getDestination()));

    // Encode and add the path elements.
    for (final String p : getPath(request.getRequestType(), request.getIdentifiers())) {
        urlBuilder = urlBuilder.addPathSegment(p);
    }//from   www .j a  v a2  s  .  c  o m

    // Encode and add the query parameters, toString() values as we go.
    for (final Map.Entry<String, ?> e : request.getParameters().entrySet()) {
        urlBuilder = urlBuilder.addQueryParameter(e.getKey(), e.getValue().toString());
    }
    final HttpUrl url = urlBuilder.build();

    final String token = request.getSession() == null ? "" : request.getSession().getToken();
    final String authorization = "Basic " + ByteString.of((apiKey + ":" + token).getBytes()).base64();

    final String contentType = "application/json";
    final String body = getBody(request.getRequestType(), request.getEntity());

    // Construct the HTTP request.
    final com.squareup.okhttp.Request httpRequest = new com.squareup.okhttp.Request.Builder().url(url)
            .method(getMethod(request.getRequestType()),
                    body == null ? null : RequestBody.create(MediaType.parse(contentType), body))
            .header("User-Agent", USER_AGENT).header("Content-Type", contentType).header("Accept", contentType)
            .header("Authorization", authorization).build();

    // Prepare a HTTP client instance to execute against.
    final OkHttpClient client = this.client.clone();

    // Interceptors fire in the order they're declared.
    // Note: Compress first, so we don't re-compress for retried requests.
    if (this.compressRequests) {
        client.interceptors().add(GzipRequestInterceptor.INSTANCE);
    }
    final int maxAttempts = request.getMaxAttempts() < 1 ? this.maxAttempts : request.getMaxAttempts();
    client.interceptors().add(new RetryInterceptor(maxAttempts));

    // Log the outgoing request.
    if (log.isDebugEnabled()) {
        log.debug("Request: Method{" + httpRequest.method() + "} URL{" + httpRequest.urlString() + "} Headers{"
                + httpRequest.headers().toString() + "} Body{" + body + "}");
    }

    // Send the request and retrieve a response.
    client.newCall(httpRequest).enqueue(new Callback() {
        @Override
        public void onFailure(final com.squareup.okhttp.Request httpRequest, final IOException e) {
            // Log the request failure reason.
            if (log.isDebugEnabled()) {
                log.debug("Request Failed", e);
            }

            deferred.callback(new ErrorResponse(e.getMessage(), e, request));
        }

        @Override
        public void onResponse(final @NonNull com.squareup.okhttp.Response httpResponse) throws IOException {
            switch (httpResponse.code()) {
            // Good response with body.
            case HttpURLConnection.HTTP_OK:
                final String responseBody = httpResponse.body().string();

                // Log the incoming response.
                if (log.isDebugEnabled()) {
                    log.debug("Response Success: Method{" + httpResponse.request().method() + "} URL{"
                            + httpResponse.request().urlString() + "} Code{" + httpResponse.code()
                            + "} Message{" + httpResponse.message() + "} Headers:{"
                            + httpResponse.headers().toString() + "} Body{" + responseBody + "}");
                }

                final T entity = codec.deserialize(responseBody, request.getResponseType());
                deferred.callback(new SuccessResponse<>(request, httpResponse.code(), responseBody, entity));
                break;

            // Good response, no body.
            case HttpURLConnection.HTTP_NO_CONTENT:
            case HttpURLConnection.HTTP_CREATED:
                // Log the incoming response.
                if (log.isDebugEnabled()) {
                    log.debug("Response Success: Method{" + httpResponse.request().method() + "} URL{"
                            + httpResponse.request().urlString() + "} Code{" + httpResponse.code()
                            + "} Message{" + httpResponse.message() + "} Headers:{"
                            + httpResponse.headers().toString() + "}");
                }

                deferred.callback(new SuccessResponse<>(request, httpResponse.code(), null, null));
                break;

            // Error response.
            default:
                final String errorBody = httpResponse.body().string();

                // Log the incoming response.
                if (log.isDebugEnabled()) {
                    log.debug("Response Error: Method{" + httpResponse.request().method() + "} URL{"
                            + httpResponse.request().urlString() + "} Code{" + httpResponse.code()
                            + "} Message{" + httpResponse.message() + "} Headers:{"
                            + httpResponse.headers().toString() + "} Body{" + errorBody + "}");
                }

                @SuppressWarnings("ThrowableResultOfMethodCallIgnored")
                final ErrorDetails error = errorBody.isEmpty()
                        ? new ErrorDetails(httpResponse.code(),
                                httpResponse.message() == null ? "unknown" : httpResponse.message(), null)
                        : codec.deserialize(errorBody, ErrorDetails.class);
                deferred.callback(new ErrorResponse(error.getMessage(), error, request));
            }

            // Indicate that application-layer response processing is complete.
            httpResponse.body().close();
        }
    });

    return deferred;
}

From source file:com.ibm.mobilefirstplatform.clientsdk.android.core.api.Request.java

License:Apache License

@Override
protected Callback getCallback(final ResponseListener listener) {
    final RequestBody requestBody = savedRequestBody;
    final Request request = this;
    final Context ctx = this.context;

    return new Callback() {
        @Override/*from   w  w  w  .j a va  2  s.c  o  m*/
        public void onFailure(com.squareup.okhttp.Request request, IOException e) {
            if (listener != null) {
                listener.onFailure(null, e, null);
            }
        }

        @Override
        public void onResponse(com.squareup.okhttp.Response response) throws IOException {
            if (listener == null) {
                return;
            }

            AuthorizationManager authorizationManager = BMSClient.getInstance().getAuthorizationManager();
            int responseCode = response.code();
            Map<String, List<String>> responseHeaders = response.headers().toMultimap();
            boolean isAuthorizationRequired = authorizationManager.isAuthorizationRequired(responseCode,
                    responseHeaders);

            if (isAuthorizationRequired) {
                if (oauthFailCounter++ < 2) {
                    authorizationManager.obtainAuthorization(ctx, new ResponseListener() {
                        @Override
                        public void onSuccess(Response response) {
                            // this will take the auth hader that has been cached by obtainAuthorizationHeader
                            request.sendRequest(listener, requestBody);
                        }

                        @Override
                        public void onFailure(Response response, Throwable t, JSONObject extendedInfo) {
                            listener.onFailure(response, t, extendedInfo);
                        }
                    });
                } else {
                    listener.onFailure(new ResponseImpl(response), null, null);
                }
            } else {
                if (response.isSuccessful() || response.isRedirect()) {
                    listener.onSuccess(new ResponseImpl(response));
                } else {
                    listener.onFailure(new ResponseImpl(response), null, null);
                }
            }
        }
    };
}

From source file:com.ibm.mobilefirstplatform.clientsdk.android.core.internal.BaseRequest.java

License:Apache License

protected Callback getCallback(final ResponseListener listener) {
    return new Callback() {
        @Override/*  w w w  . jav a2 s . c  om*/
        public void onFailure(Request request, IOException e) {
            listener.onFailure(null, e, null);
        }

        @Override
        public void onResponse(com.squareup.okhttp.Response response) throws IOException {
            if (response.isSuccessful() || response.isRedirect()) {
                listener.onSuccess(new ResponseImpl(response));
            } else {
                listener.onFailure(new ResponseImpl(response), null, null);
            }
        }
    };
}

From source file:com.j1024.mcommon.network.Http.java

License:Open Source License

public static void get(final String url, final StringCallback callback) {
    L.d(TAG, "Do GET --> " + url);
    final Request request = new Request.Builder().url(url).tag(url).build();
    client.newCall(request).enqueue(new Callback() {
        @Override// w ww .j a v  a 2s. c  o m
        public void onFailure(final Request request, final IOException e) {
            handler.post(new Runnable() {
                @Override
                public void run() {
                    callback.onFailure(request, ResultCode.NetworkException, e);
                }
            });
        }

        @Override
        public void onResponse(Response response) {
            try {
                final String responseString = response.body().string();
                L.v(TAG, "[" + url + "] response:" + responseString);
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        callback.onResponse(responseString);
                    }
                });
            } catch (final IOException e) {
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        callback.onFailure(request, ResultCode.NetworkException, e);
                    }
                });
            } catch (final JsonSyntaxException e) {
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        callback.onFailure(request, ResultCode.ServerException, e);
                    }
                });
            }
        }
    });
}

From source file:com.j1024.mcommon.network.Http.java

License:Open Source License

public static <T> void get(final String url, final JsonArrayCallback<T> jsonArrayCallback) {
    L.d(TAG, "Do GET --> " + url);
    final Request request = new Request.Builder().url(url).tag(url).build();
    client.newCall(request).enqueue(new Callback() {
        @Override// ww w. j  a  v a  2  s  .  c  o m
        public void onFailure(final Request request, final IOException e) {
            handler.post(new Runnable() {
                @Override
                public void run() {
                    jsonArrayCallback.onFailure(request, ResultCode.NetworkException, e);
                }
            });
        }

        @Override
        public void onResponse(Response response) {
            try {
                final String responseString = response.body().string();
                L.v(TAG, "[" + url + "] response:" + responseString);
                Gson gson = new Gson();
                Type token = $Gson$Types.newParameterizedTypeWithOwner(null, ArrayList.class,
                        jsonArrayCallback.getGenericType());
                final List<T> list = gson.fromJson(responseString, token);
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        jsonArrayCallback.onResponse(list);
                    }
                });
            } catch (final IOException e) {
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        jsonArrayCallback.onFailure(request, ResultCode.NetworkException, e);
                    }
                });
            } catch (final JsonSyntaxException e) {
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        jsonArrayCallback.onFailure(request, ResultCode.ServerException, e);
                    }
                });
            }
        }
    });
}

From source file:com.j1024.mcommon.network.Http.java

License:Open Source License

public static <T> void get(final String url, final JsonObjectCallback<T> jsonObjectCallback) {
    L.d(TAG, "Do GET --> " + url);
    final Request request = new Request.Builder().url(url).tag(url).build();
    client.newCall(request).enqueue(new Callback() {
        @Override/*w  ww.  j a va 2 s.c om*/
        public void onFailure(final Request request, final IOException e) {
            handler.post(new Runnable() {
                @Override
                public void run() {
                    jsonObjectCallback.onFailure(request, ResultCode.NetworkException, e);
                }
            });
        }

        @Override
        public void onResponse(Response response) throws IOException {
            try {
                final String responseString = response.body().string();
                L.v(TAG, "[" + url + "] response:" + responseString);
                Gson gson = new Gson();
                Class<T> clazz = jsonObjectCallback.getGenericType();
                final T respObj = gson.fromJson(responseString, clazz);
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        jsonObjectCallback.onResponse(respObj);
                    }
                });
            } catch (final IOException e) {
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        jsonObjectCallback.onFailure(request, ResultCode.NetworkException, e);
                    }
                });
            } catch (final JsonSyntaxException e) {
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        jsonObjectCallback.onFailure(request, ResultCode.ServerException, e);
                    }
                });
            }
        }
    });
}

From source file:com.jkenneth.droidovpn.ui.activity.MainActivity.java

License:Open Source License

/** Displays the updated list of VPN servers */
private void getServerList() {
    mCall = mClient.newCall(mRequest);/*w ww.j a  v  a  2s .  c om*/
    mCall.enqueue(new Callback() {

        @Override
        public void onFailure(Request request, IOException e) {
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    mSwipeRefreshLayout.setRefreshing(false);
                }
            });
        }

        @Override
        public void onResponse(Response response) throws IOException {
            if (response.isSuccessful()) {
                final List<Server> servers = CSVParser.parse(response);
                mHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        mServers.clear();
                        mServers.addAll(servers);
                        mDatabase.save(servers);

                        sort(mSortedBy);

                        mSwipeRefreshLayout.setRefreshing(false);
                    }
                });
            }
        }
    });
}