0

I'm trying to send username and password as basic authorization with JsonObjectRequest. I've tried to Override getHeaders() method but it didn't work. Here is my code:

public class NewPostRequest extends JsonObjectRequest {

    public NewPostRequest(JSONObject requestBody) {
        super(Method.POST, APIConstants.CREATE_POST_URL, requestBody, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {

                try {

                    long postId = response.getLong("id");

                    NewPostResponse newPostResponse = new NewPostResponse(postId);

                    EventBus.getDefault().post(newPostResponse);

                } catch (JSONException e) {

                    e.printStackTrace();

                    EventBus.getDefault().post(new NewPostResponse(-1));

                }

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

                EventBus.getDefault().post(new NewPostResponse(-1));

            }
        });
    }

    @Override
    public Map<String, String> getHeaders() throws AuthFailureError {

        Map<String, String> headers = new HashMap<>();

        String credentials = "****:***********************";

        String auth = "Basic "
                + Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP);

        headers.put("Content-Type", "application/json; charset=utf-8");

        headers.put("Authorization", auth);

        return headers;
    }

    @Override
    protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {

        JSONObject jsonObject = null;

        try {

            String data = new String(response.data,
                    HttpHeaderParser.parseCharset(response.headers));

            jsonObject = new JSONObject(data);

        } catch (UnsupportedEncodingException | JSONException e) {

            e.printStackTrace();

        }

        return Response.success(jsonObject, HttpHeaderParser.parseCacheHeaders(response));
    }
}

Error when i used Base64.NO_WRAP:

com.android.volley.AuthFailureError

And when i used Base64.DEFAULT:

java.lang.IllegalArgumentException: Unexpected char 0x0a at 46 in header value: Basic *************************

Note: This web service is working on Google Postman tool.

Ibrahim Disouki
  • 2,642
  • 4
  • 21
  • 52

1 Answers1

-4

Check my answer its working fine for me.

Check this one

Community
  • 1
  • 1
sunil
  • 796
  • 1
  • 8
  • 28