I'm writing a code to read the bytes of a request body and this requires knowing the Content-Length or Transfer-encoding ahead of time to safely transfer the message to the client. According to the RCF2616 Section 14.13:
Any Content-Length greater than or equal to zero is a valid value.
In my code Implementation, I achieved this by getting the Content-Length: header field which returns 0,which I guess is a valid response but not the required amount of bytes. Have tried in the below code to read the InputStream from the socket still the amount is achieved but this seem to be failing.Any pointers achieving this? Can provide more code if necessary.
Here is the calling method to get content-length header and read the bytes in chunk till the exact amount is achieved:
//Gets the Content-Length header value
int contLengthOffset = Integer.parseInt(newRequest.getHeaderField("Content-Length"));
int Offset = contLengthOffset;
if(Offset >= 0) {
//Any Content-Length greater than or equal to zero is a valid value.
count = QueryStreamClass.ReadFullyHelper(socket.getInputStream(), Offset);
}
Below is the method that reads the content-length:
/**
* Read the content-length to determine the transfer-length of the message.
* We need enough bytes to get the required message.
* @param Stream
* @param size
*/
public static String ReadFullyHelper(InputStream Stream, int size) {
int Read;
int totalRead = 0;
int toRead = GMInjectHandler.buffer;;
StringBuilder Request = new StringBuilder();
if(toRead > size) {
toRead = size;
}
while(true) {
try {
final byte[] by = new byte[toRead];
Read = Stream.read(by, 0, toRead);
if(Read == -1){
break;
}
Request.append(new String(by, 0, Read));
totalRead += Read;
if (size - totalRead < toRead) {
toRead = size - totalRead;
}
if (totalRead == size) {
break;
}
} catch (IOException e) {
Log.e(TAG, "Error reading stream", e);
}
}
return Request.toString();
}
contLengthOffsetwhen there is no 'offset' about it? - user207421