我創建應用程序發送文本到服務器,並檢查if(text != null)
返回新的文本值。如何從PHP服務器獲取字符串到Android?
我的代碼要做到這一點,如:
在PHP服務器:
$text = $_POST["text1"];
if($text != null){
echo "Contact1-----".$text."-----10h49 25/03/2016 at New York city";
} else{
echo "";
}
之前,我保存在服務器上的文件和所有數據寫入該文件。 這時候,我想讓它回到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();
}
我不知道爲什麼answer
是null
。
我認爲它必須返回如數據:
Contact1 $text 10h49 25/03/2016 at New York city
如果您在瀏覽器中打開anyexample.com/main.php?text1=asd會發生什麼? – Eduard7
@ Eduard7它沒有顯示任何東西。你認爲發生在PHP文件? – vanloc
嘗試將$ _POST [「text1」]更改爲$ _GET [「text1」] – Eduard7