2012-02-02 53 views
5

我想通過POST從機器人發送一個PHP數組到PHP的服務器,我有這樣的代碼發送PHP數組與POST的Android

HttpClient httpclient = new DefaultHttpClient(); 
HttpPost httppost = new HttpPost(url); 
StringEntity dades = new StringEntity(data); 
httppost.setEntity(dades); 

// Execute HTTP Post Request 
HttpResponse response = httpclient.execute(httppost); 
HttpEntity resEntity = response.getEntity(); 
return resEntity.getContent(); 

我認爲PHP的陣列可能在 StringEntity dades = new StringEntity(data); 去(數據是php數組)。誰能幫我?

+0

我通常這樣做http://www.androidsnippets.com/executing-a-http-post-request-with-httpclient – jsaye 2012-02-02 18:12:24

+0

@jsaye:該資格作爲答案,把代碼,一些解釋鏈接下來得到一些代表 – konsolenfreddy 2012-02-03 06:45:31

+0

@ konsolenfreddy:謝謝你的建議,我真的很新,有時我不知道該怎麼辦 – jsaye 2012-02-03 08:52:05

回答

6
public void postData() { 
// Create a new HttpClient and Post Header 
HttpClient httpclient = new DefaultHttpClient(); 
HttpPost httppost = new HttpPost("http://www.yoursite.com/script.php"); 

try { 
    // Add your data 
    //you can add all the parameters your php needs in the BasicNameValuePair. 
    //The first parameter refers to the name in the php field for example 
    // $id=$_POST['id']; the second parameter is the value. 
    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); 
    nameValuePairs.add(new BasicNameValuePair("id", "12345")); 
    nameValuePairs.add(new BasicNameValuePair("stringdata", "AndDev is Cool!")); 
    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 

    // Execute HTTP Post Request 
    HttpResponse response = httpclient.execute(httppost); 

} catch (ClientProtocolException e) { 
    // TODO Auto-generated catch block 
} catch (IOException e) { 
    // TODO Auto-generated catch block 
}} 

上面的代碼將發送一個這樣的數組: [id=12345, stringdata=AndDev is Cool!]

如果你想有一個bidimentional數組,你應該這樣做

Bundle b= new Bundle(); 
b.putString("id", "12345"); 
b.putString("stringdata", "Android is Cool"); 
nameValuePairs.add(new BasicNameValuePair("info", b.toString())); 

這將創建一個包含數組的數組:

[info=Bundle[{id=12345, stringdata=Android is Cool}]] 

我希望這是你想。

+0

但我想發送一個二維數組... – 2012-02-03 08:56:04

+3

http://www.coderanch.com/t/533566/Android/Mobile/sending-array-namevaluepairs-http-post這裏是解決方案! – 2012-02-03 15:18:35

9

你可以做這樣的事情:

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

,其中顏色是你的數組變量。數組標籤後面只有用戶[]並放置了值。例如。如果您的數組標籤名稱是colour,則使用它如colour[]並將值放入循環中。

+1

我有5 Arraylist ID,名稱,地址等,那麼我怎麼可以在單列表或數組中添加這個所有值? – PankajAndroid 2013-11-18 04:52:10