patternjavaMinor
Manually parsing HTTP response header
Viewed 0 times
headerresponsemanuallyparsinghttp
Problem
Due to some constraints I had to manually parse an HTTP response coming out of a stream.
I could not use buffered reader or scanner because the perform buffering and end up buffering bytes beyond the response header itself.
I'll be hitting my AWS S3 and only expect 200 or 206 status response.
This seems to work, but I'd appreciate some review.
I could not use buffered reader or scanner because the perform buffering and end up buffering bytes beyond the response header itself.
I'll be hitting my AWS S3 and only expect 200 or 206 status response.
This seems to work, but I'd appreciate some review.
final InputStream reader = socket.getInputStream();
stringBuilder.setLength(0);
//first fetch header
while (true) {
final char read = (char) reader.read();
if (read 4 &&
stringBuilder.charAt(currentCount - 1) == '\n' &&
stringBuilder.charAt(currentCount - 2) == '\r' &&
stringBuilder.charAt(currentCount - 3) == '\n' &&
stringBuilder.charAt(currentCount - 4) == '\r') {
break; //response consumed
}
}
//print the header
final String completeResponse = stringBuilder.toString();
Log.i("Downloader", completeResponse);Solution
This is a bit surprising:
Seeing the posted code starting with this is fishy,
as it suggests that there is more code before it,
and that the method is not decomposed enough,
and should be multiple methods instead.
This is a bit surprising:
The
I suggest to change this check to `read
stringBuilder.setLength(0);Seeing the posted code starting with this is fishy,
as it suggests that there is more code before it,
and that the method is not decomposed enough,
and should be multiple methods instead.
This is a bit surprising:
final char read = (char) reader.read();
if (read < 1) {The
read() method returns -1 in case of EOF.I suggest to change this check to `read
- A method that consumes the remaining lines
Code Snippets
stringBuilder.setLength(0);final char read = (char) reader.read();
if (read < 1) {MiscUtils.closeAndIgnore(socket, reader);if (read == '\n')
break; //status header fetchedif (!(status.contains("200") || status.contains("206"))) {Context
StackExchange Code Review Q#101306, answer score: 5
Revisions (0)
No revisions yet.