Say you call an HTTP request that returns a byte array which contains a binary file, how would you do this? First things first. Access it using an HttpURLConnection object. Once you have connected to the URL, get the InputStream object and that is when you will be able to convert the stream into a byte array. Check the code below.

Java

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

URLu=newURL("MY URL");

HttpURLConnection uc=(HttpURLConnection)u.openConnection();

StringcontentType=uc.getContentType();

intcontentLength=uc.getContentLength();

if(contentType.startsWith("text/")||contentLength==-1){

thrownewIOException("This is not a binary file.");

}

InputStream raw=uc.getInputStream();

InputStream in=newBufferedInputStream(raw);

byte[]data=newbyte[contentLength];

intbytesRead=0;

intoffset=0;

while(offset<contentLength){

bytesRead=in.read(data,offset,data.length-offset);

if(bytesRead==-1)break;

offset+=bytesRead;

}

in.close();

The data variable is the byte array. You can then do whatever you like (e.g. saving it as a binary file) after you have retrieved the byte array object.

To read an HttpURLConnection’s InputStream line by line, just like what you do reading a file using a FileReader, you can use the InputStreamReader class as parameter to the BufferedReader class and do the same code you do for reading a file line by line. Take this code for example.