解决Volley中的JsonObjectRequest jsonRequest参数无法被服务端读取的问题

Posted Parasis

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了解决Volley中的JsonObjectRequest jsonRequest参数无法被服务端读取的问题相关的知识,希望对你有一定的参考价值。

服务端:SpringBoot
追溯到父类方法,发现Volley只是将 jsonRequest.toString().getBytes()作为request body发送到服务端,导致服务端无法识别

import com.android.volley.AuthFailureError;
import com.android.volley.Response;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.JsonObjectRequest;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 解决Volley中的JsonObjectRequest jsonRequest参数无法被服务端读取的问题
 * <br>
 *     服务端:SpringBoot
 *     追溯到父类方法,发现Volley只是将 jsonRequest.toString().getBytes()作为request body发送到服务端,导致服务端无法识别
 *
 */
public class MyJsonObjectRequest extends JsonObjectRequest {

    private JSONObject mRequestBody;

    public MyJsonObjectRequest(int method, String url, JSONObject jsonRequest, Response.Listener<JSONObject> listener) {
        super(method, url, jsonRequest, listener, new MyRequestErrorListener(url));

        this.mRequestBody = jsonRequest;
    }

    public MyJsonObjectRequest(String url, JSONObject jsonRequest, Response.Listener<JSONObject> listener) {
        super(url, jsonRequest, listener, new MyRequestErrorListener(url));

        this.mRequestBody = jsonRequest;
    }

    public MyJsonObjectRequest(int method, String url, JSONObject jsonRequest, Response.Listener<JSONObject> listener, Response.ErrorListener errorListener) {
        super(method, url, jsonRequest, listener, errorListener);
        this.mRequestBody = jsonRequest;
    }

    public MyJsonObjectRequest(String url, JSONObject jsonRequest, Response.Listener<JSONObject> listener, Response.ErrorListener errorListener) {
        super(url, jsonRequest, listener, errorListener);
        this.mRequestBody = jsonRequest;
    }

    @Override
    public Map<String, String> getHeaders() throws AuthFailureError {
        Map<String, String> headers = new LinkedHashMap<>();
        //让服务器识别request参数在request body中
        headers.put("Content-Type", "application/x-www-form-urlencoded");
        return headers;
    }

    @Override
    public byte[] getBody() {
        StringBuilder requestBodySb = new StringBuilder();

        //遍历JSONObject中的k-v
        Iterator<String> keys = this.mRequestBody.keys();
        try {
            boolean hasNext = keys.hasNext();
            while (hasNext) {

                String key = keys.next();
                String value = mRequestBody.get(key).toString();
                requestBodySb.append(key).append("=").append(value);

                hasNext = keys.hasNext();
                if (hasNext) {
                    requestBodySb.append("&");
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        // to bytes
        try {
            String bytes = requestBodySb.toString();
            return bytes.getBytes(PROTOCOL_CHARSET);
        } catch (UnsupportedEncodingException e) {
            VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s",
                    mRequestBody, PROTOCOL_CHARSET);
        }
        return null;
    }


}

 

 

测试代码

        JSONObject params = new JSONObject();
        try {
            params.put("username", "admin");
            params.put("password", "123456");
        } catch (JSONException e) {
            e.printStackTrace();
        }


        RequestQueue requestQueue = Volley.newRequestQueue(this.getApplicationContext());
        requestQueue.add(new MyJsonObjectRequest(
                MyJsonObjectRequest.Method.POST,
                "http://192.168.1.103:8080/test",
                params,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        Log.d(TAG, "onResponse: " + response);
                    }
                }
        ));

        requestQueue.start();

 



以上是关于解决Volley中的JsonObjectRequest jsonRequest参数无法被服务端读取的问题的主要内容,如果未能解决你的问题,请参考以下文章

Volley onErrorResponse getString偶尔返回null

在 json 对象参数 Volley post 中发送令牌头

您将在 Android Studio 项目中的何处添加 volley 库?

一起Talk Android吧(第三百三十六回: Android中的volley一)

java - 如何使用Java中的Volley库将JSON api数据放入recyclerview?

无法通过使用 Volley 库中的 Intent 从片段中移动下一个 Activity