好吧,我之前使用过POST,但我从来没有使用POST阵列。 (真)
这是POST表单:
{
"about": "about me",
"sports": [
{
"id": 1,
"level": 3
},
{
"id": 2,
"level": 4
}
]
}
所以我必须发送一个带有“about”键和值的JSONObject,以及一个也可能为null的“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);
答案 0 :(得分: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中所做的那样)