Since you are reading ASCII text, and have to deal with line breaks, you can use readers and writers, and read your data with a java.io.BufferedReader
which allows you to read line by line.
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String line = reader.readLine();
StringBuilder buffer = new StringBuilder();
while ( line != null) {
buffer.append(line);
line = reader.readLine();
// you can check here if the line is empty and decide only to read the header
// or to split your header and body into different buffers
}
String fullText = buffer.toString();
If you send text data, you can also use something similar:
PrintWriter writer = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));
writer.println("GET / HTTP/1.1");
writer.println("Header: value");
writer.println(); // end of header
...
writer.flush(); // if you need to flush the buffer before closing
writer.close(); // when done - flushes and closes
Place everything in a try-catch-finally
block with the close()
methods in the finally
(or, if you use Java 7, a try-with-resources)