2

I am currently trying to read in data from a server response. I am using a Socket to connect to a server, creating a http GET request, then am using a Buffered Reader to read in data. Here is what the code looks like compacted:

    Socket conn = new Socket(server, 80);
    //Request made here
    BufferedReader inFromServer = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    String response;
    while((response = inFromServer.readLine()) != null){
        System.out.println(response);
    }

I would like to read in the data, instead of as a String, as a byte array, and write it to a file. How is this possible? Any help is greatly appreciated, thank you.

1

4 Answers 4

4

You need to use a ByteArrayOutputStream, do something like the below code:

Socket conn = new Socket(server, 80);
        //Request made here
        InputStream is = conn.getInputStream();

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int readBytes = -1;

        while((readBytes = is.read(buffer)) > 1){
            baos.write(buffer,0,readBytes);
        }

        byte[] responseArray = baos.toByteArray();
Sign up to request clarification or add additional context in comments.

6 Comments

Thank you very much. This is very helpful. I have just one more questions however. So the way the HTTP response is formatted, is first comes the header then the file contents. So in order to make a byte array of the proper size I'd have to first parse the header and get the info, and then read the file. How would you recommend doing this?
Given your issue ill recommend a slightly different approach, 1st read the response as a text (2 parts) header and content. The convert the content of text into byte array using getBytes()
I did consider that. Would there be a difference in the time it would take to read it as a text rather than as bytes? Because my whole intention here is to calculate download speed, and whoever's code I've looked at has downloaded the file as bytes.
There would be a slight difference in time couple of ms. So if you are looking at that kind of precision then you might want to use a byte reading (into the ByteArrayOutputStream) and check the byte array for when the content start (either by converting the same into a string or by checking for the byte code equivalent of Content-Length etc) .
Do you think there is anyway I can read the file as text up until the end of the header, then continue reading as bytes? Maybe there is someway I can change the position of the InputStream so that it starts where the BufferedReader left off?
|
1

One way is to use Apache commons-io IOUtils

byte[] bytes = IOUtils.toByteArray(inputstream);

Comments

1

With plain java:

    ByteArrayOutputStream output = new ByteArrayOutputStream();

    try(InputStream stream = new FileInputStream("myFile")) {
        byte[] buffer = new byte[2048];
        int numRead;
        while((numRead = stream.read(buffer)) != -1) {
            output.write(buffer, 0, numRead);
        }
    } catch(IOException e) {
        e.printStackTrace();
    }

    // and here your bytes
    byte[] myDesiredBytes = output.toByteArray();

Comments

1

If you are not using Apache commons-io library in your project,I have pretty simple method to do the same without using it..

   /*
     * Read bytes from inputStream and writes to OutputStream,
     * later converts OutputStream to byte array in Java.
     */
    public static byte[] toByteArrayUsingJava(InputStream is)
    throws IOException{
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        int reads = is.read();

        while(reads != -1){
            baos.write(reads);
            reads = is.read();
        }

        return baos.toByteArray();

    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.