sending php array with POST android

14,422

Solution 1

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
}}

The code above will send an array like this: [id=12345, stringdata=AndDev is Cool!]

If you want a bidimentional array you should do this

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

This will create an array containing an array:

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

I hope this is what you want.

Solution 2

You can do something like this :

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

where colour is your array tag. Just use [] after your array tag and put value. Eg. if your array tag name is colour then use it like colour[] and put value in loop.

Share:
14,422
edu feliu
Author by

edu feliu

Updated on June 18, 2022

Comments

  • edu feliu
    edu feliu almost 2 years

    I want to send a php array via POST from android to php server and i have this code

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

    I think that the php array may be can go in StringEntity dades = new StringEntity(data); (data is the php array). Can anyone help me?