繁体   English   中英

使用AccountManager令牌发出Volley请求

[英]Make Volley request with AccountManager Token

我试图让Volley网络库与Android的AccountManager一起使用,我正在使用该库来获取REST API的身份验证令牌。 我的基本想法是延迟实际的Volley请求(实际上是扩展默认请求的GSONRequest),直到从AccountManager中检索到令牌为止(请参见下面的TokinzedGsonRequest)。 但是,这似乎不起作用-GC的运行方式非常疯狂,并且该应用最终由于Stackoverflow错误而崩溃。 有任何想法吗?

APIClient.java

public static void makeGsonRequest(Activity context, GsonRequest request, RequestQueue requestQueue) {
    AccountManager accountManager = AccountManager.get(context);
    Account account = getAccount(context, accountManager);

    // Delay the request until a token is available
    TokenizedGsonRequest futureRequest = new TokenizedGsonRequest(request, requestQueue);

    Bundle options = new Bundle();
    accountManager.getAuthToken(
            account,
            context.getResources().getString(R.string.authenticator_auth_type),
            options,
            context,
            futureRequest,
            null
    );
}

TokenizedGsonRequest.java(实现AccountManagerCallback)

/**
 * Wrapper around {@link .helpers.GsonRequest} for use with
 * an {@link android.accounts.AccountManager}. The actual {@link com.android.volley.Request}
 * is delayed until a token has been obtained.
 */
private static class TokenizedGsonRequest implements AccountManagerCallback<Bundle> {
    public static final String TAG = TokenizedGsonRequest.class.getSimpleName();
    private GsonRequest mRequest;
    private RequestQueue mRequestQueue;

    private TokenizedGsonRequest(GsonRequest request, RequestQueue requestQueue) {
        this.mRequest = request;
        this.mRequestQueue = requestQueue;
    }

    @Override
    public void run(AccountManagerFuture<Bundle> result) {
        Bundle bundle;
        // todo authentication error
        try {
            bundle = result.getResult();
        } catch (OperationCanceledException e) {
            e.printStackTrace();
            return;
        } catch (AuthenticatorException e) {
            e.printStackTrace();
            return;
        } catch (IOException e) {
            e.printStackTrace();
            return;
        }
        String authToken = bundle.getString(AccountManager.KEY_AUTHTOKEN);
        if (!TextUtils.isEmpty(authToken)) {
            Log.d(TAG, "Received authentication token " + authToken);
            try {
                // Since Volley request urls are final, we have to copy the existing one
                String tokenUrl = API.appendQueryParameter(mRequest.getUrl(), API.TOKEN, authToken);
                GsonRequest requestCopy = new GsonRequest<>(
                        mRequest.getMethod(),
                        tokenUrl,
                        mRequest.getClass(),
                        mRequest.getHeaders(),
                        mRequest.getRequestObject(),
                        mRequest.getListener(),
                        mRequest.getErrorListener() // todo wrap error listener for retry on 400
                );
                // Retain the original request tag for cancellation
                requestCopy.setTag(TAG);
                mRequestQueue.add(requestCopy);
            } catch (AuthFailureError e) {
                Log.d(TAG, e.getMessage());
                // todo bubble up
            }
        } else {
            // todo authentication error
        }
    }
}

我自己解决了问题,并通过使用基于标头的身份验证将身份验证的Volley请求与AccountManager集成在一起。 事实证明,使用GSON时克隆请求的效果不佳,因为参数化信息会丢失。

APIClient.java

/**
 * Ensures to authenticate a given {@link com.android.volley.Request} through the
 * {@link android.accounts.AccountManager}.
 * @param request
 * @param listener
 */
public void makeRequest(Request request, AuthenticatedRequestCallback.AuthenticationErrorListener listener) {
    AccountManager accountManager = AccountManager.get(mContext);
    Account account = getAccount(accountManager);

    // Delay the request until a token from the account manager is available
    request.setRetryPolicy(new TokenRetryPolicy());
    AuthenticatedRequestCallback requestCallback = new AuthenticatedRequestCallback(
            request, mRequestQueue, listener);

    // Retrieve token and execute initial request
    Bundle options = new Bundle();
    accountManager.getAuthToken(
            account,
            mContext.getResources().getString(R.string.authenticator_auth_type),
            options,
            mContext,
            requestCallback,
            null
    );
}

AuthenticatedRequestCallback.java

/**
 * Wrapper around {@link com.votilab.votiapp.helpers.GsonRequest} for use with
 * an {@link android.accounts.AccountManager}. The actual {@link com.android.volley.Request}
 * is executed when an authentication token has been obtained.
*/
public class AuthenticatedRequestCallback implements AccountManagerCallback<Bundle> {
public static final String TAG = AuthenticatedRequestCallback.class.getSimpleName();

public static final String AUTH_TOKEN_PARAM = "token";
public static final String AUTH_TOKEN_HEADER = "X-Auth-Token";

private Request mRequest;
private RequestQueue mRequestQueue;

private final AuthenticationErrorListener mErrorListener;

/**
 * Callback interface to listen for errors thrown by the
 * {@link android.accounts.AccountManager}.
 */
public interface AuthenticationErrorListener {
    public void onAuthenticationError(AuthenticatorException e);
}

public AuthenticatedRequestCallback(Request request,RequestQueue requestQueue,
                                    AuthenticationErrorListener listener) {
    this.mRequest = request;
    this.mRequestQueue = requestQueue;
    this.mErrorListener = listener;
}

@Override
public void run(AccountManagerFuture<Bundle> result) {
    Bundle bundle;
    try {
        bundle = result.getResult();
    } catch (OperationCanceledException | IOException e) {
        if (mErrorListener != null) {
            mErrorListener.onAuthenticationError(new AuthenticatorException(e.getMessage()));
        }
        return;
    } catch (AuthenticatorException e) {
        if (mErrorListener != null) {
            mErrorListener.onAuthenticationError(e);
        }
        return;
    }

    String authToken = bundle.getString(AccountManager.KEY_AUTHTOKEN);

    if (!TextUtils.isEmpty(authToken)) {
        Log.d(TAG, "Received authentication token " + authToken); // todo remove log message
        try {
            ((AuthorizableRequest) mRequest)
                    .addHeader(AUTH_TOKEN_HEADER, authToken);
        } catch (ClassCastException e) {
            throw new ClassCastException(mRequest.toString()
                    + " must implement " + AuthorizableRequest.class.getSimpleName());
        }
        // Queue the request for execution
        mRequestQueue.add(mRequest);
    } else {
        if (mErrorListener != null) {
            mErrorListener.onAuthenticationError(
                    new AuthenticatorException("Authentication token is empty."));
        }
    }
}

}

AuthorizableRequest.java

/**
 * An interface for implementation in a {@link com.android.volley.Request} to
 * support custom authentication headers.
 */
public interface AuthorizableRequest {

    public void addHeader(String header, String value);

}

假设扩展了AbstractAccountAuthenticator的自定义Authenticator的正确实现,您应该能够在进行身份验证的同时从这样的活动发出请求:

mApiClient.makeRequest(someVolleyRequest, new AuthenticatedRequestCallback.AuthenticationErrorListener() {
                @Override
                public void onAuthenticationError(AuthenticatorException e) {
                    // something went wrong in the account manager
                }
            });

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM