Reputation: 69
I'm building a java server which have to handle http requests. I'm trying to handle a GET request and it works partially fine. In the specific case I want to discuss here I want to respond with a Json. This is what i'm doing:
private Socket socket;
OutputStream outputStream = socket.getOutputStream();
String json = gson.toJson(conversazione);
String response =
"HTTP/1.1 200 OK" + CRLF +
"Content-Length: " + (json.getBytes().length)+ CRLF +
"Content-Type: application/json;charset=UTF-8" + CRLF +
"Server: Federico's Java Server" + CRLF +
"Date: " + new Date() + CRLF + CRLF +
json + CRLF + CRLF;
outputStream.write(response.getBytes());
It works, i mean the client receive the status 200 OK but it receive a text instead of the Json. I'm doing a request with Postman and this is what it receive as response:
Upvotes: 0
Views: 1685
Reputation: 109567
Are you sure CRLF = "\r\n"? It looks inverted.
"\n\r" might be interpreted as two lines (Unix+MacOS), hence the HTTP header ends after the first line.
Also better call .getBytes(StandardCharsets.UT8).
Upvotes: 1
Reputation: 295
I think the issue you have is that you are sending the HTTP Headers and the body together, they need to be separate.
A found this article after a quick search which demonstrates this. From the code sample in that article (slightly adjusted to use the values in your sample):
PrintWriter out = new PrintWriter(socket.getOutputStream());
BufferedOutputStream dataOut = new BufferedOutputStream(connect.getOutputStream());
String content = "application/json;charset=UTF-8";
byte[] fileData = json.getBytes();
int fileLength = (int) file.length();
// send HTTP Headers
out.println("HTTP/1.1 200 OK");
out.println("Server: Federico's Java Server");
out.println("Date: " + new Date());
out.println("Content-type: " + content);
out.println("Content-length: " + fileLength);
out.println(); // blank line between headers and content, very important !
out.flush(); // flush character output stream buffer
dataOut.write(fileData, 0, fileLength);
dataOut.flush();
I encourage to go check that article out. My sample above was written manually and my not work as expected.
Upvotes: 0