使用POST android发送php数组

edu*_*liu 5 php arrays post android 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();
Run Code Online (Sandbox Code Playgroud)

我认为php数组可能会进入 StringEntity dades = new StringEntity(data); (数据是php数组).谁能帮我?

Vip*_*hit 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"));  
Run Code Online (Sandbox Code Playgroud)

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


jsa*_*aye 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
}}
Run Code Online (Sandbox Code Playgroud)

上面的代码将发送如下数组: [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())); 
Run Code Online (Sandbox Code Playgroud)

这将创建一个包含数组的数组:

[info=Bundle[{id=12345, stringdata=Android is Cool}]]
Run Code Online (Sandbox Code Playgroud)

我希望这就是你想要的.

  • http://www.coderanch.com/t/533566/Android/Mobile/sending-array-namevaluepairs-http-post这里是解决方案! (3认同)