使用 Volley 请求发送认证信息

Send authentication information with Volley request

在我的 Android 应用程序中,我必须调用如下所示的 Web 服务

http://mywesite.com/demo/mob/getmenubycategory/1

我正在使用凌空发送请求,但结果是VolleyError 401。 我已经覆盖 getParams() 方法来添加 header,但它不起作用。

这是我的代码。

RequestQueue requestQueue = volleySingleton.getRequestQueue();
    requestQueue.add(new JsonObjectRequest(Request.Method.GET, url, new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject response) {
            Log.e(TAG, "onResponse = \n " + response.toString());
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Log.e(TAG, "response error \n" + error.networkResponse.statusCode);
        }
    }) {
        @Override
        protected Map<String, String> getParams() throws AuthFailureError {
            try {
                Map<String, String> map = new HashMap<String, String>();
                String key = "Authorization";
                String encodedString = Base64.encodeToString(String.format("%s:%s", "USERNAME", "Password").getBytes(), Base64.NO_WRAP);
                String value = String.format("Basic %s", encodedString);
                map.put(key, value);
                return map;
            } catch (Exception e) {
                Log.e(TAG, "Authentication Filure" );
            }
            return super.getParams();
        }
    });

当我使用我的浏览器时,它会显示一个对话框来输入我的用户名和密码。如何使用 Volley 将用户名和密码与请求一起发送。

像我在下面使用的那样使用 CustomVolleyRequest

public class CustomVollyRequest extends Request<JSONObject> {
    private Listener<JSONObject> listener;
    private Map<String, String> params;

    public CustomVollyRequest(String url, Map<String, String> params, 
            Listener<JSONObject> reponseListener, 
            ErrorListener errorListener) {
        super(Method.GET, url, errorListener);
        this.listener = reponseListener;
        this.params = params;
    }

    public CustomVollyRequest(int method, String url, Map<String, String> params, 
            Listener<JSONObject> reponseListener, 
            ErrorListener errorListener) {
        super(method, url, errorListener);
        this.listener = reponseListener;
        this.params = params;
    }

    @Override
    protected Map<String, String> getParams() throws com.android.volley.AuthFailureError {
        return params;
    }

    @Override
    protected void deliverResponse(JSONObject response) {
        listener.onResponse(response);
    }

    @Override
    protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
        try {
            String jsonString = new String(response.data,     HttpHeaderParser.parseCharset(response.headers));
            return Response.success(new JSONObject(jsonString),
                HttpHeaderParser.parseCacheHeaders(response));
        } catch (UnsupportedEncodingException e) {
            return Response.error(new ParseError(e));
        } catch (JSONException je) {
            return Response.error(new ParseError(je));
    }
}

使用上面class如下

Map<String, String> params = new HashMap<>();
params.put("key",value);//put your parameters here
CustomVollyRequest jsObjRequest = new CustomVollyRequest(
        Request.Method.POST, url, params,
        new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                //Log.d("Response: ", response.toString());
            }
        }, 
        new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError response)
            {
                Log.d("Response: Error", response.toString());
            }
        }
);

对于身份验证,恕我直言,您应该覆盖 getHeaders 而不是 getParams,请尝试以下操作:

@Override
public Map<String, String> getHeaders() throws AuthFailureError {
       Map<String, String> headers = new HashMap<>();                
       String credentials = "username:password";
       String auth = "Basic "
                        + Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP);
       headers.put("Content-Type", "application/json");
       headers.put("Authorization", auth);
       return headers;
}

希望对您有所帮助!

只需覆盖此方法

 @Override
        public Map<String, String> getHeaders() {
            String username ="danish@gmail.com";
            String password = "dani3173";
            String auth =new String(username + ":" + password);
            byte[] data = auth.getBytes();
            String base64 = Base64.encodeToString(data, Base64.NO_WRAP);
            HashMap<String, String> headers = new HashMap<String, String>();
            headers.put("Authorization",base64);
            headers.put("accept-language","EN");
            headers.put("Content-type","application/json");
            headers.put("Accept","application/json");
            return headers;
        }