Search code examples
javaphpinputstream

InputStream.available() strange behavior


I have the source code of a running project - that is unfortunately already deployed to customers. The following Java code is running the update process :

public void downloadChanges() throws IOException {
  try (InputStream is = WebClient.doRawRequest(HttpMethod.GET, machinePath + "/update/", null)) { //IOexception is thrown outside
            if (is.available() == 0) {
                logInfo("Nothing downloaded");
            }
            
                   //continue with downloaded stuff
        }
    }

I now need to code a new backend for that. I do not know why the heck is.available() always returns 0. I found out about InputStream.available() doesn't work but as changing the java code is no option here I opened a new thread.

I tried adding some debugging code for testing in the Java Code, so it would look like this :

           if (is.available() == 0) {
                byte[] data = is.readNBytes(2048 * 1024);
                String content = new String(data, StandardCharsets.UTF_8);
                System.out.println(content);
            System.out.println("Nothing downloaded.");
            return;
       }

In this case, I get the complete and correct answer by my php software.

Anyone got ideas how to set up my php correctly to work with is.available? I can't change the java code and need to get my server running, no matter how hacky this will be. We can't visit every customer all over the world....


Solution

  • Thank you guys for helping me out !

    Answers are :

    The available() method is not intended to do what you want to do with it. There is no way to setup the php software to make the method do what you want. If you want to save the content of an InputStream to a local file, just use Files.copy, if you want read it into a byte array, use is.readAllBytes() – Holger

    WebClient.doRawRequest() will send the request to the server and immediately return the InputStream. Since the InputStream will only have data available once the server has processed the request and delivered data a call to is.available() will return 0 (since at that moment reading data will block). There is nothing you can do on the PHP side to change this. – Thomas Kläger

    Im trying to close this topic now.