Click to See Complete Forum and Search --> : QUESTION: http post


xusword
January 17th, 2007, 11:20 AM
The following code is supposed to execute a PostMethod and return the response stream.

I am having trouble getting respond body as a stream and return.


int connectionStatus;
try {
connectionStatus = client.executeMethod(post);
}
catch (Exception e){/*throw some exception*/}

InputStream result;

try{
result = post.getResponseBodyAsStream();
}
catch(IOException e){/*throw some exception*/}
finally{
post.releaseConnection();
}

if (connectionStatus == HttpStatus.SC_OK ){
return result;
}
else{/*throw some exception*/}


seems like if I release connection before returning the stream, the stream will be closed. If I do it after, the stream will be empty.

What should I do to get the stream or do I have to return byte array instead?

gmagoss
January 18th, 2007, 02:00 AM
In this method you make the variable result 'point' to the ResponseStream

result = post.getResponseBodyAsStream() ;

This does not copy the content of the stream or anything like that.
After that you release the connection and than you return result.
Naturally, since the connection is released the stream should be empty or not longer available.

you have to read the stream, before you release the connection.
That is the idea behind your assumption regarding the byte[] I guess.
You are right about that, although you don't necessarily have to use a byte[]. You could read the content and write it to another OutputStream, (ByteArrayOutputStream, FileOutputStream). Than open an Input Stream on that and return the InputStream.