【问题标题】:Send Array of objects using HttpPost in Android在 Android 中使用 HttpPost 发送对象数组
【发布时间】:2015-02-06 03:30:49
【问题描述】:

我有一个通过 HttpPost 将对象发送到 api 的应用程序。我有一些示例:

List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(4);
nameValuePairs.add(new BasicNameValuePair("Destination", destination));
nameValuePairs.add(new BasicNameValuePair("Description", description));
nameValuePairs.add(new BasicNameValuePair("CreatorName ", myName));

在这个对象中,我有一个“用户”对象数组,其中包含一个 DisplayName 和一个电话。如何通过 HttpPost 发送此数组?服务器无法识别以下内容(引号被转义):

nameValuePairs.add(new BasicNameValuePair("Users", "[{"Destination":"St.Louis", "Phone":"1234"}]"));

【问题讨论】:

  • “引号在哪里转义?”你是什么意思?
  • 对不起,我的意思是在实际代码中它看起来像这样: nameValuePairs.add(new BasicNameValuePair("Users", "[{"\"Destination\"":"\"St.Louis \"", "\"电话\"":"\"1234\""}]"));
  • 尝试阅读this one

标签: java android http-post httpclient


【解决方案1】:

最简单的方法是将数组转换为字符串(或 JSON 字符串)。然后在作为实体传递后使用您的服务器对其进行编码。

【讨论】:

    【解决方案2】:

    试试这个

    DefaultHttpClient httpclient = new DefaultHttpClient();
    HttpPost httppostreq = new HttpPost(wurl);
    
    StringEntity se = new StringEntity(nameValuePairs.toString());
    se.setContentType("application/json;charset=UTF-8");
    se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json;charset=UTF-8"));
    
    httppostreq.setEntity(se);
    HttpResponse httpresponse = httpclient.execute(httppostreq);
    

    【讨论】:

      【解决方案3】:

      我认为这段代码应该可以工作。

      nameValuePairs.add(new BasicNameValuePair("user[0]", gson.toJson(users.get(0))));
      nameValuePairs.add(new BasicNameValuePair("user[1]", gson.toJson(users.get(1))));
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-10-17
        • 2021-01-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多