使用POST android发送php数组

时间:2012-02-02 18:07:20

标签: php android arrays post http-post

我想通过POST从android发送一个php数组到php服务器,我有这个代码

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数组)。任何人都可以帮助我吗?

2 个答案:

答案 0 :(得分:11)

您可以这样做:

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

其中color是您的数组标记。只需在数组标记后使用[]并输入值即可。例如。如果您的数组标记名称为colour,则将其用作colour[],并将值放入循环中。

答案 1 :(得分:7)

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

我希望这就是你想要的。