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


How to get string from PHP server to Android?

我创建应用程序以向服务器发送文本,并检查if(text != null)是否返回新的文本值。

我这样做的代码:

在PHP服务器中:

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

之前,我在服务器上保存了一个文件,并将所有数据写入该文件。此时,我希望它能返回到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

我认为它必须返回如下数据:

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

离开Android部分,先调试PHP代码。你没有发布数据,所以这绝对是错误的:

$text = $_POST["text1"];

改为使用$_GET["text1"]:

$text = $_GET["text1"];

不过,您可以使用$_REQUEST,但IMO这是一种糟糕的做法,因为它合并了$_GET、$_POST和$_COOKIE变量。

更换

$text = $_POST["text1"];带有

$text = $_REQUEST['text1'];

设置connection.setDoInput(true);