urbanspr1nter urbanspr1nter - 3 months ago 15
HTTP Question

Sending image (or binary data) over sockets in Java

I am writing an HTTP server for fun from scratch (trying to learn HTTP more indepth) and have gotten the server to send to the client an HTTP response with HTML without much of an issue.

The problem comes when I try to send binary data such as a JPEG image over the wire. The browser cannot seem to be interpreting it correctly. I have set the MIME type of my response to

for this, and along with the correct
, I am still not able to correctly transmit the data.

A bit stumped on this and was wondering if maybe my understanding or approach to how binary data is read in Java is incorrect?

The general approach I am doing is I am reading the file from disk into a
and then reading the data into a 1024 byte buffer. As I am reading into the buffer, I am writing the buffered data into a
which has the client's socket connection as the
. I am flushing and closing the data after using it.

The portion in which I am generating my body for my HTTP response is here:

FileInputStream fis = new FileInputStream("www/server.jpg");
byte[] buffer = new byte[1024];
DataOutputStream dos = new DataOutputStream(this.clientSocket.getOutputStream());
int read;
while((read=fis.read(buffer)) >= 0) {
dos.write(buffer, 0, read);



I have hardcoded a few things, but I think this generally gets my question across. So, when I make an HTTP request shown below, I receive the following response:

enter image description here

And in FireFox the image tries to render but I get the message:
enter image description here

The image I want to display is:
enter image description here

Anyone have any ideas?



So, @rkosegi's comment about downloading the file from curl helped me figure out what the issue was. Apparently I was constructing my response body incorrectly. What happened was that there was a new line inserted before the body content after my HTTP entity headers. After removing this extra newline before streaming the body content, I was able to have the browser interpreted the data correctly.