2012-09-11 46 views
0

我正在嘗試使用HttpClient API對服務器進行JSON調用。代碼sinppet如下所示。在HTTP POST中設置參數

HttpClient httpClient = new DefaultHttpClient(); 
HttpGet httpPost = new HttpPost(URLString); 
HttpResponse response = httpClient.execute(httpPost); 
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); 
nameValuePairs.add(new BasicNameValuePair("method", "completeUserLogin")); 
String[] params = new String[]{"100408"}; 
response = httpClient.execute(httpPost); 

我想添加params到nameValuePairs。 BasicNameValuePair類不允許添加數組。有什麼想法嗎?

在此先感謝!

+0

你應該嘗試的數組轉換爲通過後預期的字符串表示,並隨後將其加入。 – CasualT

+0

你知道什麼,只是看jeet的答案。 :) – CasualT

回答

1

如果您以json格式發佈數據,那麼您不應該發佈像這樣的參數。相反,創建一個JSONObject將這些值放入該json對象中,並從該json對象中獲取一個字符串,然後創建一個StringEntity,並將此實體設置爲HttpPost對象。

的請求創建的JSONObject:

JSONObject json=new JSONObject(); 
json.put("method", "completeUserLogin"); 
JSONArray arr= new JSONArray(); 
arr.put("100408"); 
json.put("params", arr); 

String params=json.toString(); 
6

看看這個。在這裏他們傳遞了BasicNameValuePairs中的數組。這裏的顏色是我們要在服務器上發送的數組。你應該使用你的數組varible而不是顏色。

List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); 
nameValuePairs.add(new BasicNameValuePair("colours[0]","red")); 
nameValuePairs.add(new BasicNameValuePair("colours[1]","white")); 
nameValuePairs.add(new BasicNameValuePair("colours[2]","black")); 
nameValuePairs.add(new BasicNameValuePair("colours[3]","brown")); 

httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 
response = httpClient.execute(httpPost); 
+0

謝謝!你讓我走了。 – Renjith

相關問題