为什么无法在服务器上调用php文件?

问题描述 投票:0回答:1

我想在Android Studio的服务器上运行php-file。该文件将向数据库添加一个字符串,如果成功,则返回值“ 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());
}
java server bufferedreader
1个回答
0
投票

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

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.outPrintStream,并且在写入行终止符时可以将PrintStream配置为“自动刷新”。

  • 在您的带有println(c)的版本中,您是adding行终止符。

  • 当您从命令行运行代码时,System.out返回时,main可能正在刷新。

Android Studio控制台的行为是……很好……无论如何。但是,对于您的代码而言,对控制台/控制台模拟器的工作方式进行假设不是一个好主意。当您要确保数据到达需要的位置时,请终止行,或显式地flush()close()输出流。

© www.soinside.com 2019 - 2024. All rights reserved.