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 know what am I doing wrong. Any suggestion? Thank you
Socket socket = new Socket(servername, 80);
DataOutputStream bw = new DataOutputStream(new DataOutputStream(socket.getOutputStream()));
bw.writeBytes("GET "+filename+" HTTP/1.1\n");
bw.writeBytes("Host: "+servername+":80\n\n");
DataInputStream in = new DataInputStream(socket.getInputStream());
OutputStream dos = new FileOutputStream("testtttt.jpg");
int count;
byte[] buffer = new byte[2048];
while ((count = in.read(buffer)) != -1)
{
dos.write(buffer, 0, count);
dos.flush();
}
dos.close();
System.out.println("image transfer done");
socket.close();
}
URL
andHttpURLConnection
here and avoid all the HTTP-implementing code altogether. – user207421