android-Volley JSONObjectRequest return 401 error

1.3k Views Asked by At

I'm trying to send a POST request with paramteres to server. But the post params are always null.

I've tried few solutions from stackoverflow but it didn't work.

I get Unexpected response code 401 for 11.urlname

Map<String, String> jsonParams = new HashMap<String, String>();
jsonParams.put("username", "[email protected]");
jsonParams.put("usertype", "userType");
jsonParams.put("apikey", "key");

JsonObjectRequest myRequest = new JsonObjectRequest(Request.Method.POST,apiURL, new JSONObject(jsonParams),

    new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject response) {
            try {
                String status=response.getString("status");

                if (status.equals("success"))
                {
                    txtResponse.setText("Valid user");
                }
                else {
                    txtResponse.setText("InValid USer");
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

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

    @Override
    public Map<String, String> getHeaders() throws AuthFailureError {
        HashMap<String, String> headers = new HashMap<String, String>();
        headers.put("Content-Type", "application/json; charset=UTF-8");
        return headers;
    }
};
AppController.getInstance().addToRequestQueue(myRequest, "tag");

My App controller code is

public class AppController extends Application {
    public static final String TAG = AppController.class.getSimpleName();

    private RequestQueue mRequestQueue;

    private static AppController mInstance;

    @Override
    public void onCreate() {
        super.onCreate();
        mInstance = this;
    }

    public static synchronized AppController getInstance() {
        return mInstance;
    }

    public RequestQueue getRequestQueue() {
        if (mRequestQueue == null) {
            mRequestQueue = Volley.newRequestQueue(getApplicationContext());
        }

        return mRequestQueue;
    }

    public <T> void addToRequestQueue(Request<T> req, String tag) {
        req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
        getRequestQueue().add(req);
    }

    public <T> void addToRequestQueue(Request<T> req) {
        req.setTag(TAG);
        getRequestQueue().add(req);
    }

    public void cancelPendingRequests(Object tag) {
        if (mRequestQueue != null) {
            mRequestQueue.cancelAll(tag);
        }
    }
}
1

There are 1 best solutions below

0
On

If your issue has not been solved, you can refer to the following code to build your request body (params)

    private String buildRequestBody(Object content) {
        String output = null;
        if ((content instanceof String) ||
                (content instanceof JSONObject) ||
                (content instanceof JSONArray)) {
            output = content.toString();
        } else if (content instanceof Map) {
            Uri.Builder builder = new Uri.Builder();
            HashMap hashMap = (HashMap) content;
            if (isValid(hashMap)) {
                Iterator entries = hashMap.entrySet().iterator();
                while (entries.hasNext()) {
                    Map.Entry entry = (Map.Entry) entries.next();
                    builder.appendQueryParameter(entry.getKey().toString(), entry.getValue().toString());
                    entries.remove(); // avoids a ConcurrentModificationException
                }
                output = builder.build().getEncodedQuery();
            }
        }

        return output;
    }

Then...

    Map<String, String> stringMap = new HashMap<>();    
    stringMap.put("username", "yourusername");
    stringMap.put("password", "yourpassword");
    ...
    String requestBody = buildRequestBody(stringMap);