解決Volley中的JsonObjectRequest jsonRequest參數無法被服務端讀取的問題

來源:互聯網
上載者:User

標籤:方法   org   pen   class   解決   ams   roi   toc   protoc   

服務端: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參數無法被服務端讀取的問題

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.