Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sending php array with POST android

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?

like image 502
edu feliu Avatar asked Feb 02 '12 18:02

edu feliu


2 Answers

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.

like image 200
Vipul Purohit Avatar answered Oct 15 '22 07:10

Vipul Purohit


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.

like image 45
jsaye Avatar answered Oct 15 '22 08:10

jsaye