无休止地接收分块数据

arf*_*rfo 6 android http chunked chunked-encoding

您可能知道在HTTP标头中发送分块文件,没有内容长度,因此程序必须等待0才能理解该文件已结束.

--sample http header  
POST /some/path HTTP/1.1
Host: www.example.com  
Content-Type: text/plain  
Transfer-Encoding: chunked  
25  
This is the data in the first chunk  
8
sequence  
0
Run Code Online (Sandbox Code Playgroud)

为了接收该文件,可以使用以下代码.

ResponseHandler<String> reshandler = new ResponseHandler<String>() {
    public String handleResponse(HttpResponse response) throws ClientProtocolException, IOException {

        HttpEntity entity = response.getEntity();

        InputStream in =  entity.getContent();
        byte[] b = new byte[500];
        StringBuffer out = new StringBuffer();
        int len = in.read(b);
        out.append(new String(b, 0 , len));

        return out.toString();
    }
}; 
Run Code Online (Sandbox Code Playgroud)

但在我的情况下,我使用流媒体通道,换句话说没有0表明文件已经结束.无论如何,如果我使用这个代码,它似乎永远等待0永远不会发生.我的问题是有没有更好的方法从流通道接收分块文件?

arf*_*rfo 1

好的。我可以使用简单的方法接收数据(如下所示并且不使用响应处理程序)。无论如何,我仍然对 apache ChunkedInputStream以及它如何在普通输入流可以处理分块数据时有用感到有点困惑。

is =  entity.getContent();
StringBuffer out = new StringBuffer();
byte[] b = new byte[800];
int len = is.read(b);
out.append(new String(b, 0 , len));
result = out.toString();
Run Code Online (Sandbox Code Playgroud)