How to get String response from JSONObject in Volley

只愿长相守 提交于 2019-12-22 06:30:03

问题


I have created JSONRequest by using volley, It successfully hits the service, I checked the service end, It receives the data, and send "Success" in return.

The problem is that, Service returns String in output, and Volley excepts some JSON Data in output. So it executes the onError Method, instead of onResponse.

Kindly guide me how to make it accept string response, or is it not possible when you are using JSONObjectas request.

    Request<JSONObject> jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, "http://192.168.0.101:8888/api/services/mytest",
            jsonParent, new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject response) {
            Log.d("Success", response.toString());
            deleteFile();
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Log.d("Error", error.toString());
            deleteFile();
        }

    RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
    requestQueue.add(jsonObjectRequest);

回答1:


You can use StringRequest instead JSONRequest.

StringRequest stringRequest = new StringRequest(methodType, url,
                    new Response.Listener<String>() {
                        @Override
                        public void onResponse(String response) {

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

                }
            }){
                @Override
                public Map<String, String> getHeaders() throws AuthFailureError {
                    return headers == null ? super.getHeaders() : headers;
                }

                @Override
                public byte[] getBody() throws AuthFailureError {
                    return "Your JSON body".toString().getBytes();
                }
            };

getheaders method is to add custom headers if you want and getBody to supply request body.



来源:https://stackoverflow.com/questions/41870844/how-to-get-string-response-from-jsonobject-in-volley

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!