首页 > 解决方案 > 为什么调用服务器上的 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());
}

标签: javaserverbufferedreader

解决方案


鉴于您的评论,我认为这将解决问题。

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()


推荐阅读