【问题标题】:POST JSON array body to .NET web service using Volley in Android在 Android 中使用 Volley 将 JSON 数组主体发布到 .NET Web 服务
【发布时间】:2014-01-20 16:56:12
【问题描述】:

我正在尝试在 Android 中使用 Volley 发布一个 JSON 正文,在花了很多时间但没有成功之后,我正在写这个问题。

下面是我的代码sn-p

StringRequest residentSyncRequest = new StringRequest(Request.Method.POST, Commons.URL,this,this,ADD_REQ){
    @Override
    public Map<String, String> getHeaders() throws AuthFailureError {

        HashMap<String,String> params = new HashMap<String, String>();
        params.put("Content-Type","application/json");

        return params;
    }

    @Override
    public byte[] getBody() throws AuthFailureError {
        JSONArray jsonArray = new JSONArray();
        JSONObject jsonObject = new JSONObject();

        SharedPreferences sharedPreferences = getActivity().getSharedPreferences(Commons.PREF_NAME, Context.MODE_PRIVATE);

        try {
            jsonObject.put("RowID","0");
            jsonObject.put("LocalID","100");
            jsonObject.put("LoginUserID",sharedPreferences.getString(Commons.pref_loginUserId,""));                      
            jsonObject.put("AppToken",sharedPreferences.getString(Commons.pref_appToken,""));

        } catch (JSONException e) {
            e.printStackTrace();
        }

        jsonArray.put(jsonObject);

        return jsonArray.toString().getBytes();
    }
};
VollyRequest.getRequestQueue(getActivity()).add(residentSyncRequest);

我收到以下回复

E/Volley﹕ [255] BasicNetwork.performRequest: Unexpected response code 400 for ...

我尝试使用 postman chrome 扩展程序调用相同的 Web 服务,该服务运行良好。

不确定在返回byte[]之前是否需要进行任何编码。

请帮忙。

提前致谢。

【问题讨论】:

    标签: android json web-services http-post android-volley


    【解决方案1】:

    Volley 不像 JsonObject 请求那样直接支持 JsonArray 请求。希望他们可以在下一个版本中添加这个功能,因为有很多 api 只提供 JsonArray。

    编辑:

    其实有解决办法here

    【讨论】:

      【解决方案2】:

      默认情况下,Volley 将所有发布参数作为 JSON 值,因此您只需要使用请求而不是 StringRequest,只需添加您想要发布的所有 JSON 值作为常规发布值。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-02-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-02-14
        • 1970-01-01
        相关资源
        最近更新 更多