【问题标题】:Send List<Integer> with POST method in Android在 Android 中使用 POST 方法发送 List<Integer>
【发布时间】:2015-01-17 20:03:31
【问题描述】:

我必须使用我的 post 方法将整数列表发送到 Web 服务。该服务重新排序此列表并将其返回给我。到目前为止,该服务运行良好。我已经在 SoapUI 中对其进行了测试,它成功地重新排序了我的列表并返回。但是,我无法在 Android 上使用它。更详细的,我有清单;

List<Integer> productIds;

我写了如下方法来调用服务;

public void getSortedProductIds(boolean sync, AsyncHttpResponseHandler handler, List<Integer> productIds, Activity context) throws JSONException, UnsupportedEncodingException {
    initClient(sync);

    JSONObject jsonParams = new JSONObject();
    jsonParams.put("productIds", productIds);
    StringEntity entity = new StringEntity(jsonParams.toString());
    System.out.println(entity);
    httpClient.post(context, WS_BASE_URL + "picker/sortbycategory", entity, "application/json",
            handler);
    return;

}

在 Android 端,我执行以下操作来运行此代码;

getSortedProductIds(true, new AsyncResponseHandler() {                          
    @Override
    public void onSuccess(int status, Header[] header, byte[] response) {
        JSONObject jsonObj = ResponseUtils.byteArrayToJsonObj(response);
        JSONArray jsonArr;
        try {
            jsonArr = jsonObj.getJSONArray("result");
            for (int i = 0; i < jsonArr.length(); i++) {
                System.out.println(jsonArr.getInt(i));
                }
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                }
            }

    @Override
    public void onFailureAction(int status, Header[] header, byte[] responseBody, Throwable exception) {
        System.out.println("fail");
        }
}, productIds, this);

但是它总是以onFailure 方法结束。我无法从 SA 上的任何解决方案中获得帮助。这里可能有什么问题?我们如何使用 post 方法发送整数列表?谢谢

【问题讨论】:

    标签: android json post arraylist


    【解决方案1】:

    问题解决了。问题是我想发送一个整数数组,但是我发送了一个服务端无法识别的 JSON 对象;

    jsonParams.put("productIds", productIds);
    

    此 JSON 对象包含正确的值且有效,但服务直接需要一个数组(JSON 数组)。它无法知道该对象内有一个带有“productIds”键的数组。所以,我不得不发送一个 JSONArray。首先我形成了我的 JSON 数组;

    JSONArray x = new JSONArray();
    for(Integer productId : productIds){
        x.put(productId);
    }
    

    然后我创建了 StringEntity 并通过 post 方法传递它。

    StringEntity entity = new StringEntity(x.toString());
    httpClient.post(context, WS_BASE_URL + "picker/sortbycategory", entity, "application/json",
        handler);
    

    如果有人遇到这样的问题,只需以 JSON 格式发送确切的对象/数组。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多