繁体   English   中英

如何在Android中使用Volley使用发布参数发出JSONArray请求

[英]How to make a JSONArray Request with post param using volley in Android

这是获取组的方法:

public void getGroupsThree() {
        String tag_json_obj = "json_obj_obj"; /* tag used to cancel the request */
        String loginUrl = "removed for security reasons"; /* login rest url */

        /* show the progress bar */
        PD = new ProgressDialog(getActivity());
        PD.setMessage("Loading...");
        PD.show();

        /* this are the params to post */
        Map<String, String> params = new HashMap<String, String>();
        params.put("userID", "13");
        params.put("secretKey", "andrew");
        params.put("starts", "5");
        params.put("limits", "10");

        CustomRequestJsonArray jsonArr;
        jsonArr = new CustomRequestJsonArray(Request.Method.POST, loginUrl, null,
                new Response.Listener<JSONArray>() {
                    @Override
                    public void onResponse(JSONArray response) {

                        for(int i = 0; i < response.length(); i++) {
                            try {
                                JSONObject groupData = (JSONObject) response.get(i);
                                Toast.makeText(getActivity(), "Response: " + groupData.getString("groupID"), Toast.LENGTH_LONG).show();
                            } catch (JSONException e) {
                                Toast.makeText(getActivity(), "Json Error: " + e.getMessage(), Toast.LENGTH_LONG).show();
                            }

                        }
                        PD.hide();
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                /* handle request error */
                Toast.makeText(getActivity(), "Response " + error.getMessage(), Toast.LENGTH_LONG).show();
                PD.hide();
            }
        }, params);

        /* add the request to the request queue */
        VolleyApplication.getInstance().addToRequestQueue(jsonArr, tag_json_obj);

    }

这是我的CustomRequestJsonArray类

public class CustomRequestJsonArray extends JsonRequest<JSONArray> {


    private Response.Listener<JSONArray> listener;
    private Map<String, String> params;

    public CustomRequestJsonArray(int method, String url, String requestBody,
                                  Response.Listener<JSONArray> listener, Response.ErrorListener errorListener,Map<String, String> params) {
        super(method, url, requestBody, listener,
                errorListener);
        this.params = params;
    }

    @Override
    protected Map<String, String> getParams() throws com.android.volley.AuthFailureError {
        return params;
    };

    @Override
    protected void deliverResponse(JSONArray response) {
        listener.onResponse(response);
    }

    @Override
    protected Response<JSONArray> parseNetworkResponse(NetworkResponse response) {
        try {
            String jsonString = new String(response.data,
                    HttpHeaderParser.parseCharset(response.headers));
            return Response.success(new JSONArray(jsonString),
                    HttpHeaderParser.parseCacheHeaders(response));
        } catch (UnsupportedEncodingException e) {
            return Response.error(new ParseError(e));
        } catch (JSONException je) {
            return Response.error(new ParseError(je));
        }
    }



}

响应错误为

“ JSONObject无法转换为JSONArray”

我认为这些参数没有发布。 这是期望:

[
  {
    "groupID": "28",
    "userID": "13",
    "name": "ACS Test Edit",
    "description": "Edited by Joe",
    "createdOn": "2015-09-29 08:55:49",
    "active": "1"
  },
  {
    "groupID": "25",
    "userID": "13",
    "name": "ICT consulting",
    "description": "",
    "createdOn": "2015-09-28 07:32:33",
    "active": "1"
  }
]

如果发生任何错误,例如无效的安全密钥或缺少参数,我应该得到以下信息:

{
  "code": "404",
  "error": "You are not permitted to access this resource"
}

当我运行该应用程序时,将得到以下结果:

由以下原因引起:org.json.JSONException:值{“ error”:“您无权访问此资源”,“ code”:“ 404”}类型为org.json.JSONObject的对象无法转换为JSONArray

所以,我这个参数没有被发布。 如何确定它们已发布?

因为成功时服务器应用程序的响应是JSONArray ,错误是JSONObject ,而您想使用JsonArrayRequest ,所以我建议您的parseNetworkResponse如下所示:

@Override
protected Response<JSONArray> parseNetworkResponse(NetworkResponse response) {
    try {
        String jsonString = new String(response.data,
                HttpHeaderParser.parseCharset(response.headers, "utf-8"));
        // Check if it is JSONObject or JSONArray
        Object json = new JSONTokener(jsonString).nextValue();
        JSONArray jsonArray = new JSONArray();
        if (json instanceof JSONObject) {
            jsonArray.put(json);
        } else if (json instanceof JSONArray) {
            jsonArray = (JSONArray) json;
        }
        return Response.success(jsonArray,
                HttpHeaderParser.parseCacheHeaders(response));
    } catch (UnsupportedEncodingException e) {
        return Response.error(new ParseError(e));
    } catch (JSONException e) {
        return Response.error(new ParseError(e));
    }
}

关于错误消息You are not permitted to access this resource ,也许您错过了请求标头中的凭据。 如果标头中包含您的凭据,则应在Postman中检查您的请求。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM