Android volley How to send a request with both authentication headers and a Json object in the body

I need to send a volley http request with an authentication header and a Json object in the body. Boo, I did not find a request for this in a salvo.

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?

+4
source share
3

Request getHeaders()

, getParams() getBody()

:

HTTP Android Volley

+9

@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

getHeaders() getParams() .

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);

!

0

All Articles