Search code examples
javaserverbufferedreader

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


I want to run php-file on a server from Android Studio. The file will add a string to the database and return the value 'success' if successful. I don’t see the point in uploading php-file – it processes a POST request. There are absolutely no errors in it. At first I made this code in the console and it worked perfectly. But when I copied it to Android Studio, it turned out that "D/NetworkSecurityConfig: No Network Security Config specified, using platform default". This is strange because I just ran the same code in the console and there were no errors. But now the most interesting thing: if you replace the cycle that reads the input stream by reading one line, the error disappears. How it works? I thought that there was a request limitation on the server, but everything works from the console application. Maybe this is a feature of 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());
}

Solution

  • Given your comments, I think this will fix the problem.

    for (int c; (c = in.read()) >= 0;)
        System.out.print((char) c);
    System.out.println();
    
    // and get rid of the 2 statements after this.
    

    The problem appears to be that System.out is not being flushed. System.out is a PrintStream, and a PrintStream can be configured to "autoflush" when line terminator is written.

    • In your version with a println(c) you were adding a line terminator.

    • When you ran the code from the command line, System.out was probably being flushed when main returned.

    The Android Studio console behavior is ... well ... whatever it is. But it is not a good idea for your code to make assumptions about how the console / console emulator is going to work. Terminate your lines, or explicitly flush() or close() the output stream when you want to be sure that the data goes where it needs to go.