[英]How do I make a HttpPost request to RESTful webservice to pass an URL with parameters which includes an array of values?
我正在嘗試調用RESTful網絡服務以獲取JSON對象。 現在,我嘗試通過HttpGet進行呼叫並成功。 我需要傳遞的網址非常像這樣: 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);
}現在,我不確定如何在郵寄電話會議中的Details = [{“ Count”:“ 2”,“ ID”:“ 1”,“ Price”:“ 5”}]中添加值對,以及應該如何添加我執行它以獲取與進行HttpGet調用時所獲得的JSON對象相同的JSON對象。 請幫忙。
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可以選中它 。
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,然后構造需要作為參數傳遞的對象。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.