3

I am trying to fetch input stream pdf from URL Connection but I am getting an empty input stream. Can anyone please tell me what is I am doing wrong? Following is the code:

<!-- language: java -->

URL fileUrl = new URL("https://www.dropbox.com/s/ao3up7xudju4qm0/Amalgabond%20Adhesive%20Agent.pdf");
HttpURLConnection connection = (HttpURLConnection)fileUrl.openConnection();
connection.connect(); 
InputStream is = connection.getInputStream();
Log.i("TAG", "is.available(): " + is.available());

is.available() is returning 0 empty stream.

user207421
  • 305,947
  • 44
  • 307
  • 483
Mustansar Saeed
  • 2,730
  • 2
  • 22
  • 46

3 Answers3

3

According to the javadoc, available() does not block and wait until all data is available, so you might have not completely received your stuff when its called.

You should use something like this instead of available() :

int bytesRead;
byte[] buffer = new byte[100000];

while((bytesRead = is.read(buffer)) > 0){

    // Do something here with buffer
}

read() is a blocking method.

slaadvak
  • 4,611
  • 1
  • 24
  • 34
0

You're misusing the available() method. It doesn't tell you the length of the input stream, so the fact that it returns zero doesn't indicate that it's empty. See the Javadoc, where all this is explicitly stated.

Just read it until end of stream.

user207421
  • 305,947
  • 44
  • 307
  • 483
0

If your ultimate goal is to download a file from Dropbox, you should use the Dropbox Java API, or maybe this simpler solution. Otherwise, a URLConnection to a file on Dropbox will download a web page (in HTML) showing you a link to click (with a lot of other stuff !) for downloading your file.

Community
  • 1
  • 1
slaadvak
  • 4,611
  • 1
  • 24
  • 34