26

我正在查看示例和代码,但没有看到任何实现。在现阶段这可能吗?

4

3 回答 3

91

对于那些不想为此使用 Spring for Android 的人,这里是如何做到的。

@Override
public Map<String, String> getHeaders() throws AuthFailureError {
    HashMap<String, String> params = new HashMap<String, String>();
    String creds = String.format("%s:%s","USERNAME","PASSWORD");
    String auth = "Basic " + Base64.encodeToString(creds.getBytes(), Base64.DEFAULT);
    params.put("Authorization", auth);
    return params;
}

请注意,您可能必须使用Base64.NO_WRAP而不是Base64.DEFAULT它才能工作。正如评论中指出的那样。

API 8+

于 2013-09-24T11:32:39.100 回答
10

是的,这是可能的。您需要覆盖 Request.getHeaders()。我很懒,我使用 Spring for Android 的 HttpHeaders 和 HttpAuthentication ,但您可以构建 auth 标头并从方法中返回它。从 getHeaders() 您可以返回基本身份验证的身份验证标头。这是一个带有基本身份验证的示例请求。

public class GetUser extends Request<User> {

    private static final String TAG = GetUser.class.getName();

    private Response.Listener<User> mListener;
    private ObjectMapper mMapper = new ObjectMapper();

    public GetUser(Response.ErrorListener errorListener, Response.Listener<User> listener){
        super(Method.GET, PoisUtils.BASE_URL + "/users", errorListener);

        mListener = listener;
    }

    @Override
    protected Response<User> parseNetworkResponse(NetworkResponse response) {
        String jsonString = new String(response.data);
        try {
            User result = mMapper.readValue(jsonString, User.class);
            return Response.success(result, getCacheEntry());
        } catch (IOException e) {
            Log.d(TAG, e.getMessage());
        }
        return null;
    }

    @Override
    protected void deliverResponse(User response) {
        mListener.onResponse(response);
    }

    @Override
    public Map<String, String> getHeaders() throws AuthFailureError {
        return AuthUtils.buildAuthHeaders().toSingleValueMap();
    }
}

这是我构建身份验证标头的方式

public static HttpHeaders buildAuthHeaders(){

    if(UserUtils.isUserLogged()){
        HttpHeaders requestHeaders = new HttpHeaders();
        User user = PoisApplication.get().getUser();

        HttpAuthentication auth = new HttpBasicAuthentication(
                user.getUsername(), user.getPassword());
        requestHeaders.setAuthorization(auth);

        return requestHeaders;
    }
    return null;
}
于 2013-05-29T17:02:14.233 回答
0

对于代理授权(如 squid),请使用此标头:

String credentials = proxyUsername + ":" + proxyPassword;
String auth = "Basic "  + Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP);                
headers.put("Proxy-Authorization", auth);
于 2017-02-15T10:35:44.133 回答