如何将数组从Android发送到PHP Serrver

时间:2018-09-29 06:58:27

标签: php android

我有一个包含自定义对象的数组,我需要将其从Android应用发送到PHP后端。

ArrayList<CustomModel> customModels; //Filled with 200+ elements

Gson gson = new Gson();
String str = gson.toJson(customModels);
result = ((new HttpConnection()).sendDataToServer(str));

这是HTTP部分:

conn = (HttpURLConnection)url.openConnection();
conn.setReadTimeout(READ_TIMEOUT);
conn.setConnectTimeout(CONNECTION_TIMEOUT);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);


Uri.Builder builder = new Uri.Builder()
        .appendQueryParameter("data[]", data);
query = builder.build().getEncodedQuery();

现在可以完美地找到它,服务器可以获取数据,但无法读取数据。根据规范,服务器应获取Array而不是JSON String。

后端使用POST内容执行此操作:

$var1 = array_keys($_POST);

我的问题是-如何通过POST从Android向PHP发送数组?

2 个答案:

答案 0 :(得分:0)

一个例子

OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
String postData = "A=1&B=2";
writer.write(postData, 0, postData.length());
writer.close();

答案 1 :(得分:0)

您可以像这样在Php端接收阵列。

 $array = $_POST['array'];

    foreach($array as $value) {
       $array_value = $value . "<br>";
    }

您可以使用下面的类将数据发送到服务器

import android.os.AsyncTask;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;

public class BackgroundProcessPOST extends AsyncTask<Void, String, String> {

    private String url;
    private JSONObject data;


    //Constructor to initialize variables
    public BackgroundProcessPOST(String url , JSONObject data) {
        this.url = url;
        this.data = data;
    }

    //Doing Background work here
    @Override
    protected String doInBackground(Void... voids) {
        try {
            URL url = new URL(this.url); //setting url
            HttpURLConnection connection =
                    (HttpURLConnection) url.openConnection(); //opening connection to url

            connection.setRequestMethod("POST");    //setting request method

            OutputStream outputStream = connection.getOutputStream();
            BufferedWriter bufferedWriter = new BufferedWriter
                    (new OutputStreamWriter(outputStream, "UTF-8"));
            bufferedWriter.write(data.toString());
            bufferedWriter.flush();
            bufferedWriter.close();
            outputStream.close();

            InputStream inputStream;
            int code = connection.getResponseCode(); // receiving code to check
                                                    // data posted successfully or not
            if (code == HttpURLConnection.HTTP_OK) {
                inputStream = connection.getInputStream(); //if code=200 means data is OK
                                                          // we can receive response
            } else {
                inputStream = connection.getErrorStream();  // data not sent successfully,
            }

            BufferedReader bufferedReader = new BufferedReader
                    (new InputStreamReader(inputStream));
            StringBuilder builder = new StringBuilder();
            String line = "";
            while ((line = bufferedReader.readLine()) != null) {
                builder.append(line).append("\n");
            }
            return builder.toString();
        } catch (Exception e) {
            return "Exception: " + e.getMessage();
        }
    }

    //This method receives results from background and send them to MainActivity(UI)
    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        if (result.contains("Exception")) {
                 //Handle the exception here,,
        } else {
              //Handle  your data here..
        }
    }

}

现在您可以从任何活动中调用 BackgroundProcessPOST.java

    JSONObject data = new JSONObject();
    data.put("timestamp",timestamp);
    data.put("type", "Android");
   String url = "your url here..";

    new BackgroundProcessPOST(url, data, this).execute();