java - 为什么调用服务器上的 php 文件不起作用?
问题描述
我想在 Android Studio 的服务器上运行 php-file。该文件将向数据库添加一个字符串,如果成功则返回值“成功”。我没有看到上传 php 文件的意义——它处理一个 POST 请求。它绝对没有错误。起初我在控制台中编写了这段代码,它运行良好。但是当我将它复制到 Android Studio 时,结果显示“D/NetworkSecurityConfig:未指定网络安全配置,使用平台默认值”。这很奇怪,因为我只是在控制台中运行了相同的代码并且没有错误。但是现在最有趣的是:如果将读取输入流的循环替换为读取一行,错误就消失了。这个怎么运作?我认为服务器上存在请求限制,但一切都可以通过控制台应用程序进行。
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
是 a PrintStream
,并且 aPrintStream
可以在写入行终止符时配置为“自动刷新”。
在您的版本中,
println(c)
您添加了一个行终止符。当您从命令行运行代码时,返回
System.out
时可能会被刷新。main
Android Studio 控制台行为是……好吧……不管它是什么。但是,您的代码对控制台/控制台模拟器的工作方式做出假设并不是一个好主意。当您想确保数据到达它需要去的地方时,终止您的行,或明确地flush()
或输出流。close()
推荐阅读
- javascript - VueJS:无法读取未定义的属性“名称””
- java - Java/Spring 异常线程“main”java.lang.NoClassDefFoundError: org/springframework/beans/factory/ListableBeanFactory
- java - 如何将 Java AudioInputStream 写入 MP3?
- css - 如何在 Angular 项目中包含字体系列(SFUIDisplay-Regular)?
- unity3d - 网格中有大量点的大型三角形多边形
- python - 将 Pandas 数据帧合并到具有不正确输出的同一列标识符上
- android - 不幸的应用程序崩溃
- regex - 检测正则表达式是否接受另一个正则表达式的子集?
- c# - Apache SOLR 和 C# windows 应用程序
- python - 如何在 Python 中在后台打开 PDF?