-2

I have done some research, also checked answer on stackoverflow. However i just cant get my code right, please help. the code can run, but i cant get the image, it shows 0kb.

Socket socket = new Socket(addr, port);  


byte [] buffer = new byte[1024];



PrintWriter writer = new PrintWriter(socket.getOutputStream(), true);


writer.println("GET " + url.getFile() + " HTTP/1.0\r\n");
writer.println("HOST:" + url.getHost() + "\r\n");
writer.println("\r\n");


DataInputStream in = new DataInputStream(socket.getInputStream());
ByteArrayOutputStream out = new ByteArrayOutputStream();


int n = 0;
while (-1!=(n=in.read(buffer)))
{
     out.write(buffer, 0, n);
}
out.close();
in.close();
byte[] response = out.toByteArray();
FileOutputStream fos = new FileOutputStream("0.jpeg");
fos.write(response);
fos.close();
}catch (Exception e){
     System.out.println(e.toString());
}
helios
  • 12,916
  • 2
  • 41
  • 51
onegun
  • 786
  • 1
  • 9
  • 24

2 Answers2

2

Using raw sockets to perform an HTTP GET is much more complicated than necessary. I recommend using an HTTP client like the one from Apache or you can use java.net.URLConnection. See How do I do a HTTP GET in Java? or Using java.net.URLConnection to fire and handle HTTP requests

Community
  • 1
  • 1
Pino
  • 6,292
  • 5
  • 42
  • 54
  • thanks, this is my homework, only can use socket. i dont have many choice to use url connection. – onegun Sep 27 '12 at 07:09
0

Your code doesn't have any obvious flaws. If you're getting a zero length file, it's because you aren't sending anything.

BTW you don't need the ByteArrayOutputStream. You can write everything you read directly to the FileOutputStream. Saves both time and space.

user207421
  • 289,834
  • 37
  • 266
  • 440