0

I am trying to POST a JSON body using Volley in Android and after spending many hours with no success I am writing this question.

Following is mine code snippet

StringRequest residentSyncRequest = new StringRequest(Request.Method.POST, Commons.URL,this,this,ADD_REQ){
    @Override
    public Map<String, String> getHeaders() throws AuthFailureError {

        HashMap<String,String> params = new HashMap<String, String>();
        params.put("Content-Type","application/json");

        return params;
    }

    @Override
    public byte[] getBody() throws AuthFailureError {
        JSONArray jsonArray = new JSONArray();
        JSONObject jsonObject = new JSONObject();

        SharedPreferences sharedPreferences = getActivity().getSharedPreferences(Commons.PREF_NAME, Context.MODE_PRIVATE);

        try {
            jsonObject.put("RowID","0");
            jsonObject.put("LocalID","100");
            jsonObject.put("LoginUserID",sharedPreferences.getString(Commons.pref_loginUserId,""));                      
            jsonObject.put("AppToken",sharedPreferences.getString(Commons.pref_appToken,""));

        } catch (JSONException e) {
            e.printStackTrace();
        }

        jsonArray.put(jsonObject);

        return jsonArray.toString().getBytes();
    }
};
VollyRequest.getRequestQueue(getActivity()).add(residentSyncRequest);

and I am getting following response

E/Volley﹕ [255] BasicNetwork.performRequest: Unexpected response code 400 for ...

I tried to call the same web service using postman chrome extension and the service is working just fine.

Not sure if I need to do any encoding before returning byte[].

Please help.

Thanks in advance.

CRUSADER
  • 5,486
  • 3
  • 28
  • 64
Vishal Vyas
  • 2,571
  • 1
  • 22
  • 39

2 Answers2

0

Volley by default puts all post parameters as JSON Values, so you just need to use a Request and not StringRequest and just add all JSON Values you want to post as regular post values.

Lefteris
  • 14,550
  • 2
  • 56
  • 95
0

Volley doesn't support JsonArray request directly like JsonObject request.Hope they can add this function in next version because there are a lot of api only provide JsonArray.

EDIT:

Actually there is a solution here.

Community
  • 1
  • 1
Bagusflyer
  • 12,675
  • 21
  • 96
  • 179