如何使用 Volley 将 JSONObject 作为表单数据发送到服务器

How to send JSONObject to server as form-data using Volley

我将使用 Volley 库将 JsonObjectRequest 作为表单数据发送到服务器。我检查了类似的问题。 none 个解决了我的问题。

这是我需要的确切请求的 Postman 屏幕截图:

这是我的名为 myKey 的 JSONObject,它包含一个 JSONArray:

{
 "myArray":[
    {
    "code":"FA95",
    "id":"94"
    }
 ]
}

这是我的请求方法:

public static void getSomething(String url) {

    JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, url, null, new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject response) {

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

        }
    }) {
        @Override
        public byte[] getBody() {
            return super.getBody();
        }
    };

    request.setRetryPolicy(new DefaultRetryPolicy(DefaultRetryPolicy.DEFAULT_TIMEOUT_MS, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
    AppController.getInstance().addToRequestQueue(request);
}

我是否应该覆盖 getBody()?它应该 return 到底是什么?

答案如下:

您需要覆盖 getParams() 方法并使用 StringRequest 而不是 JsonObjectRequest