sending php array with POST android

前端 未结 2 584
伪装坚强ぢ
伪装坚强ぢ 2020-12-17 03:46

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          


        
相关标签:
2条回答
  • 2020-12-17 04:16
    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.

    0 讨论(0)
  • 2020-12-17 04:22

    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.

    0 讨论(0)
提交回复
热议问题