我想从 Android Studio 在服务器上运行 php 文件。该文件将向数据库添加一个字符串,如果成功则返回值“success”。我不明白上传 php 文件有什么意义——它处理 POST 请求。其中绝对没有任何错误。起初,我在控制台中编写了这段代码,它运行得很好。但是当我将其复制到Android Studio时,结果显示“D/NetworkSecurityConfig:未指定网络安全配置,使用平台默认值”。这很奇怪,因为我刚刚在控制台中运行了相同的代码并且没有错误。但现在最有趣的是:如果将读取输入流的循环替换为读取一行,错误就会消失。怎么运行的?我认为服务器上存在请求限制,但控制台应用程序一切正常。也许这是 Android Studio 的一个功能?
try {
URL url = new URL("https://educationapps.site/hello.php");
String postData = "username=" + username + "&email=" + email +
"&password=" + password + "&func=" + func;
byte[] postDataBytes = postData.getBytes(StandardCharsets.UTF_8);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length",
String.valueOf(postDataBytes.length));
conn.setDoOutput(true);
conn.getOutputStream().write(postDataBytes);
BufferedReader in = new BufferedReader(
new InputStreamReader(conn.getInputStream(),
StandardCharsets.UTF_8));
// This code does not work ↓↓↓
/*
for (int c; (c = in.read()) >= 0;)
System.out.print((char)c);
*/
// But this one works ↓↓↓
String c = in.readLine();
System.out.println(c);
} catch (Throwable throwable) {
System.out.println(throwable.getMessage());
}
最佳答案
根据您的意见,我认为这可以解决问题。
for (int c; (c = in.read()) >= 0;)
System.out.print((char) c);
System.out.println();
// and get rid of the 2 statements after this.
问题似乎是 System.out
没有被刷新。 System.out
是一个 PrintStream
,并且 PrintStream
可以配置为在写入行终止符时“自动刷新”。
在带有
println(c)
的版本中,您添加行终止符。当您从命令行运行代码时,
System.out
可能会在main
返回时被刷新。
Android Studio 控制台的行为是……好吧……不管它是什么。但是,让您的代码对控制台/控制台模拟器的工作方式做出假设并不是一个好主意。当您想确保数据到达需要的地方时,终止您的行,或者显式 flush()
或 close()
输出流。
关于java - 为什么调用服务器上的 php 文件不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62360976/