如何从 PHP 服务器获取字符串到 Android?

How to get string from PHP server to Android?

我创建应用程序来向服务器发送文本并检查 if(text != null) return 新文本值。

我的代码如下:

在 PHP 服务器中:

$text = $_POST["text1"];
if($text != null){
    echo "Contact1-----".$text."-----10h49 25/03/2016 at New York city";
} else{
    echo "";
}                      

之前,我在服务器上保存了一个文件,并将所有数据写入到这个文件中。 这时候,我想让它return回android数据,不需要保存到文件。 Android 中的代码是:

final String scripturlstring = "http://www.anyexample.com/main.php";

AddContactActivity contact;
public void sendToServer(final String text){
    contact = new AddContactActivity();
    new Thread(new Runnable() {
        @Override
        public void run() {
            try {

                String textparam = "text1=" + URLEncoder.encode(text, "UTF-8");

                URL scripturl = new URL(scripturlstring);
                HttpURLConnection connection = (HttpURLConnection) scripturl.openConnection();
                connection.setDoOutput(true);
                connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                connection.setFixedLengthStreamingMode(textparam.getBytes().length);
                contentWriter.write(textparam);
                contentWriter.flush();
                contentWriter.close();

                InputStream answerInputStream = connection.getInputStream();
                final String answer = getTextFromInputStream(answerInputStream);

                if(answer!="") {
                    String[] contactInfo = answer.split("-----");

                    contact.insertContact(contactInfo[0], contactInfo[1], contactInfo[2], "", "");
                }
                answerInputStream.close();
                connection.disconnect();


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

}



public String getTextFromInputStream(InputStream is) {
    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
    StringBuilder stringBuilder = new StringBuilder();

    String currentLine;
    try {
        while ((currentLine = reader.readLine()) != null) {
            stringBuilder.append(currentLine);
            stringBuilder.append("\n");
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

    return stringBuilder.toString().trim();
}

我不知道为什么 answernull

我认为它必须 return 这样的数据:

Contact1 $text 10h49 25/03/2016 at New York city

替换

$text = $_POST["text1"];

$text = $_REQUEST['text1'];

留下 Android 部分并先调试您的 PHP 代码。您没有发布数据,所以这绝对是错误的:

$text = $_POST["text1"];

改用 $_GET["text1"]:

$text = $_GET["text1"];

尽管您可以使用 $_REQUEST,但在我看来,这是一个不好的做法,因为它合并了 $_GET、$_POST 和 $_COOKIE 变量。

设置connection.setDoInput(true);