hc-dev mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From Ortwin Gl├╝ck <...@odi.ch>
Subject Re: java.io.StreamCorruptedException when a sending huge java object...
Date Fri, 10 Nov 2006 08:38:01 GMT

The problem is not caused by HttpClient, but because you are using the 
IO API incorrectly.

Suraj Natarajan wrote:
> int len = httpRequest.getContentLength();
> InputStream is = httpRequest.getInputStream();
> byte[] b = new byte[len] ;
> // read the entire content in one shot
> is.read(b);

Please read the API Doc of the read method. The method does not 
guarantee to read a specific number of bytes, but it will return the 
number of bytes read as an int. You must repeatedly read from the stream 
until read() returns -1.

> // construct the java object from the byte[]
> deserialize(b) ;
> If the request content length is big around 25K then a
> java.io.StreamCorruptedException is thrown during deserialization. This
> only happens when the content length is big.
> If the stream is read using the code below then it works fine even for
> huge content length.
> InputStream is = httpRequest.getInputStream();
> ByteArrayOutputStream baos = new ByteArrayOutputStream();
> while ((read = bis.read(buffer)) != -1) {
>   baos.write(buffer, 0, read);
> }
> deserialize(baos.toByteArray());

This is exactly the correct way of reading from a stream.

> Can someone please explain the problem and is there a better way do
> this?
> Thanks in advance.



[web]  http://www.odi.ch/
[blog] http://www.odi.ch/weblog/
[pgp]  key 0x81CF3416
        finger print F2B1 B21F F056 D53E 5D79 A5AF 02BE 70F5 81CF 3416

To unsubscribe, e-mail: httpclient-dev-unsubscribe@jakarta.apache.org
For additional commands, e-mail: httpclient-dev-help@jakarta.apache.org

View raw message