2013-06-24 54 views
0

我正在嘗試調用RESTful webservice來獲取JSON對象。現在我試着通過HttpGet進行通話並且成功了。我需要通過的URL非常類似於:http://example.com/ /def.xxx?Name=save &代碼=示例& OrderDetails = [{「Count」:「2」,「ID」:「1」,「Price」: 「5」}]。我如何向RESTful webservice發送HttpPost請求以傳遞包含值數組參數的URL?

`

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); 

} 現在我不知道我應該如何在詳細信息中添加值對= [{「計數」:「2」,「ID」:「1」,「價格「:」5「}]在Post調用中,我應該如何執行它以獲取與獲取HttpGet時所獲得的JSON對象相同的對象。請幫忙。

回答

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然後

作爲參數傳遞。

+0

感謝您的回答。對於OrderDetails,我需要這樣傳遞:OrderDetails = [{「Count」:「2」,「ID」:「1」,「Price」:「5」},{「Count」:「3」,「ID 「:」3「,」價格「:」3「}]。而這些都是絃樂。在這種情況下,我應該如何創建OrderDetailsObject?另外,我是否需要包含?在.ashx URL後? – MSIslam

+0

考慮到您提供的JSONARRAY示例,我嘗試了這種方式:inParameters = new ArrayList (); for(int i = 0; i )是未定義的錯誤消息 – MSIslam

+0

另外,我是否需要放置任何HttpHeader? – MSIslam

相關問題