【问题标题】:sending php array with POST android使用 POST android 发送 php 数组
【发布时间】:2012-02-25 09:57:01
【问题描述】:

我想通过 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数组)。谁能帮帮我?

【问题讨论】:

  • 我通常这样做androidsnippets.com/…
  • @jsaye: 有资格作为答案,把代码,一些解释链接下来以获得一些代表
  • @konsolenfreddy:谢谢你的建议,我真的是新来的,有时我不知道该怎么办
  • @jsaye:别担心,不过很好找!

标签: php android arrays post http-post


【解决方案1】:

你可以这样做:

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[] 一样使用它并将值放入循环中。

【讨论】:

  • 我有 5 个 Arraylist id、name、address 等,那么我如何将所有值添加到单个 List 或数组中?
【解决方案2】:
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!]

如果你想要一个双向数组,你应该这样做

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

我希望这是你想要的。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2011-04-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多