4
votes

I need to send via volley a http request with both authentification header and Json object in body. Bu I did not found a request for this in volley.

I found GsonRequest and JsonObjectRequest. GsonRequest int method, String url, Class clazz, Map headers, Listener listener, ErrorListener errorListener, Gson useGson)

JsonObjectRequest (int method, java.lang.String url, JSONObject jsonRequest, Response.Listener listener, Response.ErrorListener errorListener)

Any idea what to do ?

3

3 Answers

8
votes

In your Request class, override getHeaders() to send custom Headers

To send parameters in request body you need to override either getParams() or getBody() method of the request classes

described here:

Asynchronous HTTP Requests in Android Using Volley

1
votes

try this code

@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;
}
1
votes

Both getHeaders() and getParams() methods can be used simultaneously for sending data separately as header and body.

JsonObjectRequest jsonObjectRequest = new 
                    JsonObjectRequest(Request.Method.GET,
                    url,
                    null,
                    new Response.Listener<JSONObject>() {
                        @Override
                        public void onResponse(JSONObject response) {
                            Log.d(TAG, response.toString());
                        }
                    },
                    new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {
                            Log.d(TAG, error.toString());
                        }
                    }) {
                @Override
                public Map<String, String> getHeaders() throws AuthFailureError {
                    HashMap<String, String> headers = new HashMap<>();

                    headers.put(headerKey, headerValue);
                    return headers;
                }

                @Override
                protected Map<String, String> getParams() throws AuthFailureError {
                    Map<String, String> params = new HashMap<>();
                    params.put(bodyKey, bodyValue);
                    return params;
                }
            };
            VolleySingleton.getInstance(getActivity()).addToRequestQueue(jsonObjectRequest);

This worked for me!!