Volley使用POST方法将JSONObject发送到服务器

时间:2022-10-22 22:58:04

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

我想通过使用volley库{“user_id”:12,“answers”:{“11”:3,“12”:4,“13”:5}}将以下格式的jsonobject发送到服务器

JSONObject object = new JSONObject();

            try {
                object.put("user_id", user_id);
                JSONObject answers = new JSONObject();
               for (int i = 0; i < questions.size(); i++) {
                    JSONObject answer = new JSONObject();
                    answer.put(questions.get(i).getId(),questions.get(i).getAnswer());
                    answers.put("answers", answer);
                    object.put("answers", answer);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

If I want to use StringRequest how should I send this JsonObject to server by using POST method

如果我想使用StringRequest,我应该如何使用POST方法将此JsonObject发送到服务器

2 个解决方案

#1


6  

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<String>() {
                @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 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();
        }

#2


1  

use the following sample code

使用以下示例代码

RequestQueue queue = Volley.newRequestQueue(this);

private void serverFronJsonObjReq() {
showProgressDialog();


        Map<String, String> postParam= new HashMap<String, String>();
        postParam.put("username", "singh@gmail.com");
        postParam.put("password", "123456");


JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.POST,
        Const.BASE_URL_LOGIN, new JSONObject(postParam),
        new Response.Listener<JSONObject>() {

            @Override
            public void onResponse(JSONObject response) {
                Log.d(TAG, response.toString());
                msgResponse.setText(response.toString());
                hideProgressDialog();
            }
        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                VolleyLog.d(TAG, "Error: " + error.getMessage());
                hideProgressDialog();
            }
        }) {

    /**
      Passing some request headers
     * */
    @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;
    }



};

jsonObjReq.setTag(TAG);
// Adding request to request queue
queue.add(jsonObjReq);

// Cancelling request
/* if (queue!= null) {
queue.cancelAll(TAG);
} */

}

#1


6  

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<String>() {
                @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 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();
        }

#2


1  

use the following sample code

使用以下示例代码

RequestQueue queue = Volley.newRequestQueue(this);

private void serverFronJsonObjReq() {
showProgressDialog();


        Map<String, String> postParam= new HashMap<String, String>();
        postParam.put("username", "singh@gmail.com");
        postParam.put("password", "123456");


JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.POST,
        Const.BASE_URL_LOGIN, new JSONObject(postParam),
        new Response.Listener<JSONObject>() {

            @Override
            public void onResponse(JSONObject response) {
                Log.d(TAG, response.toString());
                msgResponse.setText(response.toString());
                hideProgressDialog();
            }
        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                VolleyLog.d(TAG, "Error: " + error.getMessage());
                hideProgressDialog();
            }
        }) {

    /**
      Passing some request headers
     * */
    @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;
    }



};

jsonObjReq.setTag(TAG);
// Adding request to request queue
queue.add(jsonObjReq);

// Cancelling request
/* if (queue!= null) {
queue.cancelAll(TAG);
} */

}