为什么调用服务器上的 php-file 不起作用?

Why the call to the php-file on the server does not work?

我想 运行 php 从 Android Studio 在服务器上归档。如果成功,该文件将向数据库添加一个字符串和 return 值 'success'。我看不出上传 php 文件有什么意义——它处理 POST 请求。绝对没有错误。起初我在控制台中编写了这段代码,它运行得很好。但是当我把它复制到AndroidStudio时,结果是"D/NetworkSecurityConfig: No Network Security Config specified, using platform default"。这是 st运行ge 因为我只是 运行 控制台中的相同代码并且没有错误。但现在最有趣的事情是:如果将读取输入流的循环替换为读取一行,错误就消失了。怎么运行的?我认为服务器上存在请求限制,但一切都在控制台应用程序中运行。也许这是 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在写行结束符的时候可以配置成"autoflush"。

  • 在带有 println(c) 的版本中,您 添加了 行终止符。

  • 当您 运行 来自命令行的代码时,System.out 可能在 main 返回时被刷新。

Android Studio 控制台的行为是......好吧......不管它是什么。但是,让您的代码假设控制台/控制台模拟器将如何工作并不是一个好主意。终止您的线路,或者明确地 flush()close() 输出流,当您想要确保数据到达它需要去的地方时。