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.
final InputStream reader = socket.getInputStream();
stringBuilder.setLength(0);
//first fetch header
while (true) {
final char read = (char) reader.read();
if (read < 1) {
//fail
MiscUtils.closeAndIgnore(socket, reader);
return false;
}
stringBuilder.append(read);
if (read == '\n')
break; //status header fetched
}
//check status
final String status = stringBuilder.toString();
Log.i("Downloader", status);
if (!(status.contains("200") || status.contains("206"))) {
//fail
MiscUtils.closeAndIgnore(socket, reader);
return false;
}
//now consume the header
stringBuilder.setLength(0);
while (true) {
final char read = (char) reader.read();
if (read < 1) {
MiscUtils.closeAndIgnore(socket, reader);
return false;
}
stringBuilder.append(read);
final int currentCount = stringBuilder.length();
if (currentCount > 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);