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.
Volley默认情况下将所有发布参数作为JSON值放置,因此您只需要使用Request而不是StringRequest,而只需添加要发布的所有JSON值作为常规发布值即可。
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 .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.