Question

I have tried to write a program that gets a file from web server in a chunked format. I am trying to use ChunkedInputStream class in HTTP 3.0 API. When I run the code, it gives me "chucked input stream ended unexpectedly" error. What am I doing wrong? Here is my code:

    HttpClient client = new DefaultHttpClient();
    HttpGet getRequest = new HttpGet(location);
    HttpResponse response = client.execute(getRequest);
    InputStream in = response.getEntity().getContent();

    ChunkedInputStream cis = new ChunkedInputStream(in);
    FileOutputStream fos = new FileOutputStream(new ile("session_"+sessionID));
    while(cis.read() != -1 )
    {
        fos.write(cis.read());
    }
    in.close();
    cis.close();
    fos.close();
Was it helpful?

Solution

Don't use the ChunkedInputStream, as axtavt suggests, but there is another problem. You are skipping every odd numbered byte. If the data is an even number of bytes you will write the -1 that means EOS and then do another read. The correct way to copy a stream:

byte[] buffer = new byte[8192];
int count;
while ((count = in.read(buffer)) > 0)
{
  out.write(buffer, 0, count);
}

OTHER TIPS

Are you sure that you need to use ChunkedInputStream in this case?

I think HttpClient should handle chuncked encoding internally, therefore response.getEntity().getContent() returns already decoded stream.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top