我正在尝试调用RESTful Web服务来获取JSON对象。现在我尝试通过HttpGet进行调用并获得成功。我需要传递的URL非常类似:http://example.com/ /def.xxx?Name=save&Code=sample&OrderDetails=[{Count“:”2“,”ID“:”1“, “价格”:“5”}]。我
`
StringBuilder URL = new StringBuilder("http://example.com/def.xxx?");
URL.append("Name="+name+"&");
URL.append("Code="+code+"&");
URL.append("Details=%5b");
int val = 0;
for (int i = 0; i<len; i++){
if (val > 0)
{URL.append(",");
}
else
val = 1;
URL.append(.....);
URLX = URL.toString();
httpGet = new HttpGet(URLX);
response = client1.execute(httpGet);
`
现在,如果我想进行HttpPost调用而不是HttpGet调用,该怎么办?我试过这种方式,
String URL = "http://example.com/def.xxx";
DefaultHttpClient client1 = new DefaultHttpClient();
HttpResponse response = null;
HttpPost httpPost = new HttpPost();
ArrayList<NameValue> postParameters;
postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("Name", name));
postParameters.add(new BasicNameValuePair("Code", code));
try {
httpPost.setEntity(new UrlEncodedFormEntity(postParameters));
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
response = client1.execute(httpPost);
} 现在我不确定如何在Post调用中添加Details = [{“Count”:“2”,“ID”:“1”,“Price”:“5”}]中的值对,我该怎么办?执行它以获得与我在进行HttpGet调用时获得的相同JSON对象。请帮忙。
答案 0 :(得分:1)
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
ArrayList<NameValuePair> postParameters;
postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("Name", name));
postParameters.add(new BasicNameValuePair("Code", sample));
构造JSONArray或JSONObject您可以checkit。
postParameters.add(new BasicNameValuePair("OrderDetails",jOrderdetails));
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
修改: - 强>
对于OrderDetailsObject,您可以按如下方式构造它。
JSONArray jOrderdetails = new JSONArray();
for(int i=0;i<len;i++){
JSONObject childObject = new JSONObject();
childObject.put("Count",countvalue);
childObject.put("ID",IDvalue);
childObject.put("Price",Pricevalue);
jOrderdetails.put(childObject).toString();
}
以上面显示的方式,你可以构造JSONArray,然后你需要作为参数传递该对象。