读取块中的字节以获得确切的Content-length

时间:2015-01-10 08:36:14

标签: java

我正在编写一个代码来读取请求体的字节,这需要提前知道Content-Length或Transfer-encoding,以便将消息安全地传输到客户端。根据RCF2616第14.13节:

  

任何大于或等于零的Content-Length都是有效值。

在我的代码实现中,我通过获取返回 0 Content-Length:标头字段来实现这一点,我猜这是一个有效的响应但不是所需的字节数。尝试过以下代码从套接字读取InputStream仍然实现了数量,但这似乎是失败的。任何指针实现这一点?如有必要,可以提供更多代码。

这是获取内容长度标头并读取块中字节的调用方法,直到达到确切数量:

//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);
                }

以下是读取内容长度的方法:

/**
 * 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();
}

1 个答案:

答案 0 :(得分:1)

'这似乎失败'不是问题描述,而是:

public static String ReadFullyHelper(InputStream Stream, int size) {

您可以将整个方法简化为以下内容:

DataInputStream din = new DataInputStream(Stream);
byte[][ buffer = new byte[size];
din.readFully(buffer);
return new String(buffer, 0, size); // or you may want to use a specific encoding here