Android,如何从httpPost请求中接收String数组

时间:2018-03-26 14:19:53

标签: php android arrays http-post

我有一个AsyncTask需要从httpPost请求得到一个字符串数组作为响应。

基本上我的请求被发送到一个php页面,"问"数据库名称列表。使用PDO我可以使用$results = $query->fetch()获取查询结果。然后我有return $results。不知道它是否会起作用。还需要了解如何从httpPost请求中获取数组。

编辑,代码:

PHP页面:

<?php 
    $servername = "servername";
    $username = "username";
    $password = "password";
    $databasename = "databasename";
    $Variable = $_POST['username'];

    try {

        $conn = new PDO("mysql:host=$servername;dbname=$databasename", $username, $password);
        $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

        $sql=$conn->query("SELECT ID FROM Table WHERE Varaible= '$Variable'");
        $control = $sql->fetch();
        $ID= $control['ID'];

        $sql2=$conn->query("SELECT Other_Variable FROM Other_Table WHERE ID_Second ='$ID'");
        $control = $sql2->fetch();


        return $control;

        $conn->exec($sql);
    } catch (PDOException $e){
        echo "Error: <br/><b>".$e->getMessage()."</b>";
    }

    $conn = null;
?>

AsyncTask类

import android.content.Context;
import android.os.AsyncTask;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;

import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;


public class GestisciPersonaggiAction extends AsyncTask<String, Void, String[]> {

    private String[] personaggi;
    private Context context;
    private URL url;
    private RecyclerView.Adapter adapter;
    private HttpURLConnection connection;
    public RecyclerView.LayoutManager layoutManager;
    private OutputStreamWriter request;
    private String username;

    public GestisciPersonaggiAction(Context context, String username){

        personaggi = new String[GlobalVariables.personaggiCreati];
        this.context = context;
        this.username = username;
        layoutManager = new LinearLayoutManager(this.context);

    }

    @Override
    protected String[] doInBackground(String... urls) {

        try{

            url = new URL(urls[0]);
            connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            connection.setRequestMethod("POST");

            request = new OutputStreamWriter(connection.getOutputStream());
            request.write("username="+username);
            request.flush();
            request.close();

            //Don't know how to get the String[] array from the php page


        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return personaggi;
    }

    protected void onPostExecute(String[] strings){

        //Should create a RecyclerLayout whith the array.

    }


}

感谢您的帮助

1 个答案:

答案 0 :(得分:0)

没有人回答我,所以我找到了另一种解决方案。

我没有从请求中获取数组,而是获取每个字符串并将其放入数组中。

所以,首先我知道数组必须有多大“大”。然后,这是代码:

@Override
    protected String[] doInBackground(String... urls) {
        while (fatto < GlobalVariables.personaggiCreati) {
               //"fatto" is initialaized as 0, the other one is how much "big" the array is
            try {

                url = new URL(urls[0]);
                connection = (HttpURLConnection) url.openConnection();
                connection.setDoOutput(true);
                connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                String parameters = "username="+username+"&indice="+fatto;
                //I pass "fatto" as a parameter so I know at which index of the array I am
                connection.setRequestMethod("POST");

                request = new OutputStreamWriter(connection.getOutputStream());
                request.write(""+parameters);
                request.flush();
                request.close();

                InputStreamReader inputStreamReader = new InputStreamReader(connection.getInputStream());
                BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
                String line = bufferedReader.readLine();
                personaggi[fatto] = line;
                inputStreamReader.close();
                bufferedReader.close();

                connection.disconnect();


            } catch (MalformedURLException e) {
                e.printStackTrace();
                return null;
            } catch (IOException e) {
                e.printStackTrace();
                return null;
            }
            fatto++;
        }

        return personaggi;
    }

    protected void onPostExecute(String[] strings){

        //There's some code to set the RecyclerView
        GestisciPersonaggi.adapter = new GPAdapter(strings);
        GestisciPersonaggi.recyclerView.setAdapter(GestisciPersonaggi.adapter);


        GestisciPersonaggi.recyclerView.setLayoutManager(layoutManager);
        GestisciPersonaggi.recyclerView.setItemAnimator(new DefaultItemAnimator());
        GestisciPersonaggi.recyclerView.addItemDecoration(new DividerItemDecoration(context, LinearLayoutManager.VERTICAL));



        GestisciPersonaggi.progressBar.setVisibility(View.INVISIBLE);

    }

还有我的php页面:

<?php 
    $servername = "servername";
    $username = "username";
    $password = "password";
    $databasename = "databasename";
    //In my table I have 2 ID. The first is the ID of the Character. The second is the ID of the player who created it. So "$Nome_Giocatore" is the username of the player, I will then get the ID of that player to take all the Characters created by that player
    $Nome_Giocatore = $_POST['username'];
    $Indice = $_POST['indice'];
    //"Indice" is the variable "fatto" we pass as parameter, it indicate the array's index we are at
    $i = 0;

    try {

        $conn = new PDO("mysql:host=$servername;dbname=$databasename", $username, $password);
        $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

        $sql=$conn->query("SELECT ID_Giocatore FROM Giocatori WHERE Nome_Giocatore ='$Nome_Giocatore'");
        $control = $sql->fetch();
        $Giocatore_Proprietario = $control['ID_Giocatore'];
        //"Giocatore_Proprietario" is litteraly "Owner_Player". So it's the "secondary" ID we talked after.

        $sql2=$conn->query("SELECT Nome_Personaggio FROM Personaggi WHERE Giocatore_Proprietario=$Giocatore_Proprietario");
        //Here I take the Character name(s)

        foreach ($sql2 as $personaggio){
            $personaggi[$i] = $personaggio['Nome_Personaggio'];
            $i++;
            //Create the Array
        }





        $realIndice = (int) $Indice;
        //Just to be sure. Sometimes I get "$Indice" as a String...

        echo $personaggi[$realIndice];

    } catch (PDOException $e){
        echo "Errore: <br/><b>".$e->getMessage()."</b>";
    }

    $conn = null;
?>