0

好的,我以前使用过 POST,但我从来不需要 POST Arrays。(真的)

这是 POST 表单:

{

    "about": "about me",
    "sports": [
    {
            "id": 1,
            "level": 3

    },

    {

             "id": 2,
             "level": 4

    }

    ]

}

所以我必须发送一个带有“about”键和值的 JSONObject,以及一个“sports”JSONArray,它也可能为空。

我尝试了以下方法:

1.

List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>();
    nameValuePair.add(new BasicNameValuePair("about", "Lorem ipsum about me"));
    nameValuePair.add(new BasicNameValuePair("sports", "[]"));

2.

  List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>();
        nameValuePair.add(new BasicNameValuePair("about", "Lorem ipsum about me"));
        nameValuePair.add(new BasicNameValuePair("sports", new ArrayList<NameValuePair>()));
                                                  ///Of course its silly it doesnt work at all

所以我的问题是如何获得这个 POST 表单?

我的发帖:

HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
httppost.addHeader("Content-Type", "application/json");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse httpResponse = httpclient.execute(httppost);
4

1 回答 1

1

在这里,我为您手动构建了 JSONObject:

try{
    JSONObject attr1 = new JSONObject("{\"id\": 1, \"level\":3 }");
    JSONArray sports = new JSONArray();
    sports.put(attr1);
    //sports.put(attr2); and so on
    JSONObject yourObject = new JSONObject("{\"about\": \"About me\"}");
    yourObject.put("sports", sports);

    String url = yourObject.toString();
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost(url);
    HttpResponse httpResponse = httpclient.execute(httppost);

}catch(Exception e){
}

如您所见,我已经从字符串构建了 json 的某些部分,但是您也可以创建一个空对象并用数据填充它(就像我在 jsonarray 的情况下所做的那样)

于 2014-06-24T22:27:43.703 回答