I am trying to download an image from a server through sockets. My code works fine, but when I download the image, the size is correct but the image does not open. I don\'t
My reputation is not enough to comment, so have to start a new answer.
ug__'s answer is great, but the line
buffer = string.substring(indexOfEOH+4).getBytes();
has some problems, the buffer will be corrupted. For example,
byte[] before = new byte[]{(byte)0xf1, (byte)0xf2, (byte)0xf3, (byte)0xf4};
String str = new String(before, 0, before.length);
byte[] after = str.getBytes();
before and after will not be the same.
So I modified ug__'s code a little bit:
OutputStream dos = new FileOutputStream("test.jpg");
int count, offset;
byte[] buffer = new byte[2048];
boolean eohFound = false;
while ((count = in.read(buffer)) != -1)
{
offset = 0;
if(!eohFound){
String string = new String(buffer, 0, count);
int indexOfEOH = string.indexOf("\r\n\r\n");
if(indexOfEOH != -1) {
count = count-indexOfEOH-4;
offset = indexOfEOH+4;
eohFound = true;
} else {
count = 0;
}
}
dos.write(buffer, offset, count);
dos.flush();
}
in.close();
dos.close();