user1150209
user1150209

Reputation: 11

Cannot read from InputStream

My current code is this:

try {
    inputStream is = (new URL(urlpath).openStream());
    ByteArrayOutputStream os = new ByteArrayOutputStream();
        for (int len; (len = is.read(data)) != -1;) {
            os.write(data, 0, len);
        }
        os.flush();
        data = os.toByteArray();
    } catch (Exception e) {
        e.printStackTrace();
    }

But is.read(data) always returns -1. I do not understand why it is not working. I used same code at other places, it is working, but in this application, this code is not working. What should be problem with the url path?

Upvotes: 1

Views: 1792

Answers (2)

jgroehl
jgroehl

Reputation: 134

InputStream will return -1 if there is no more data to be read.

See http://docs.oracle.com/javase/7/docs/api/java/io/InputStream.html#read(byte[]) for further details.

  1. Did you check the content of your request by opening it in a browser?
  2. Did you try opening the ports on your server machines firewall?
  3. Are you sure you are doing the request correctly with the framework you are using?

Try this

InputStream is = url.openConnection().getInputStream();

BufferedReader reader = new BufferedReader( new InputStreamReader( is )  );

String line = null;
while( ( line = reader.readLine() ) != null )  {
    System.out.println(line);
}
reader.close();

Upvotes: 0

Max Worg
Max Worg

Reputation: 2972

You said this code is meant to run on a server but it works in your local environment. The reason it's not working is because the server is also being provided with a localhost address and that resource is only on your local environment. Change localhost to the IP address of the host that the resource is on and your code will work.

http://localhost... <-- will tell the code to look on the same computer that the code is running on which is why the server can't find it.

Change localhost to the IP address (xxx.xxx.xxx.xxx) of the resource your web application is running on.

So if the web application is hosted on 192.168.0.100 then you would do the following:

http://192.168.0.100:8080/School/abc.jsp?selectedLetter=d~2015012200001~NOTICE~%27%27

Note that since the server needs to reach an external resource to talk to the web application firewall rules will also come into play (you will need to make sure that any firewall is not blocking port 8080 on the host the web application is running on).

Upvotes: 1

Related Questions