Volley send JSONObject to server with POST method

后端 未结 2 733
闹比i
闹比i 2020-11-29 12:43

I want to send a jsonobject with below format to server by using volley library { \"user_id\": 12, \"answers\": { \"11\": 3,

2条回答
  •  萌比男神i
    2020-11-29 13:27

    You can use the following working sample code. I have tested. Hope this helps!

           try {
                jsonBody = new JSONObject();
                jsonBody.put("Title", "VolleyApp Android Demo");
                jsonBody.put("Author", "BNK");
                jsonBody.put("Date", "2015/08/26");
                requestBody = jsonBody.toString();
    
                StringRequest stringRequest = new StringRequest(1, url, new Response.Listener() {
                    @Override
                    public void onResponse(String response) {
                        textView.setText(response);
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        textView.setText(error.toString());
                    }
                }) {
                    @Override
                    public String getBodyContentType() {
                        return String.format("application/json; charset=utf-8");
                    }
    
                    @Override
                    public byte[] getBody() throws AuthFailureError {
                        try {
                            return requestBody == null ? null : requestBody.getBytes("utf-8");
                        } catch (UnsupportedEncodingException uee) {
                            VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s",
                                    requestBody, "utf-8");
                            return null;
                        }
                    }
                };
                MySingleton.getInstance(this).addToRequestQueue(stringRequest);
            } catch (JSONException e) {
                e.printStackTrace();
            }
    

    UPDATE: To create JSONObject as your requirement, use the following:

            JSONObject jsonObject = new JSONObject();
            try {
                jsonObject.put("11", 3);
                jsonObject.put("12", 4);
                jsonObject.put("13", 5);
    
                JSONObject jsonObject2 = new JSONObject().put("answers", jsonObject);
                jsonObject2.put("user_id", 12);            
            } catch (JSONException e) {
                e.printStackTrace();
            }
    

提交回复
热议问题