我创建应用程序发送文本到服务器,并检查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