【发布时间】:2016-07-13 01:26:59
【问题描述】:
我创建应用程序以向服务器发送文本并检查 if(text != null) 返回新的文本值。
我的代码如下:
在 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 它没有显示任何内容。你认为发生在 PHP 文件中吗?
-
尝试将 $_POST["text1"] 更改为 $_GET["text1"]
-
我尝试使用
$GET["text1"] and$_REQUEST['text1'] 但我没有收到来自服务器的值。 -
不是 $GET 而是 $_GET。不要使用 $_REQUEST:stackoverflow.com/questions/1924939/…
标签: php android server postdata