Shozzking
Shozzking

Reputation: 31

Downloading files from internet using sockets

I'm trying to use sockets in java to download files from the internet. My program seems to work properly and compiles but when I go to check the file afterwards then its 0 bytes in size. I'm not sure where I'm going wrong with this.

BufferedInputStream download = new BufferedInputStream(socket.getInputStream());
FileOutputStream newFile = new FileOutputStream(fileName);
output.print("GET " + address + " HTTP/1.0\r\n\n");
output.flush();
byte[] input = new byte[10240];
int finished = download.read(input, 0, 10240);

I then have a while loop that makes sure that finished doesn't equal -1 and calls for more bytes of data while writing it to the file using:

newFile.write(input, 0, finished);

I know that my socket is configured properly since I can download and read the HTTP header with it. My program never enters the while loop to write the data, the read() function returns -1 right away. How would I go about fixing my code?

Thanks!

edit: I see that this was marked as duplicate for an answer that used the URL class to do this same thing. I cannot use URL or URLConnection.

Upvotes: 1

Views: 365

Answers (1)

user207421
user207421

Reputation: 310913

You aren't reading the headers correctly. You need to read them until you get a blank line, not a null. You're reading the entire response when you're only trying to read the headers, so there is no response body left to read in the second part.

But you have another problem with the BufferedReader. It is likely to steal data from the following body. This is a rare case for DataInputStream.readLine(), and yes I know it's deprecated.

You also aren't checking to see whether you got an HTTP error code, which would mean that there is no body in the response.

You don't need to initialize line before the while loop.

You also have a missing \r between the two \ns.

All this is why it's better to use HttpURLConnection, and if you can't it's why it's not a great assignment.

The easy way to write those loops is:

// headers
while ((line = in.readLine()) != null
{
    if (line.length() == 0)
        break; // end of headers
    // ...
}

// body
while ((count = in.read(buffer)) > 0)
{
    out.write(buffer, 0, count);
}

Upvotes: 2

Related Questions