开发者

URLConnection and content length : how much data is download?

I've created a servlet which reads the content of a file to a byte array which subsequently is written to the OutputStream of the response:

// set headers
resp.setHeader("Content-Disposition","attachment; filename=\"file.txt\"");
resp.setHeader("Content-Length", "" + fileSize);

// output file content.
OutputStream out = resp.getOutputStream();
out.write(fileBytes);
out.close();

Now, I've also written a "client" which needs to find out how big the file is. This should be easy enough as I've added the "Content-Length" header.

URLConnection conn = url.openConnection();
long fileSize = co开发者_Go百科nn.getContentLength();

However, I am a little uncertain about the big picture. As I understand my own servlet, the entire file content is dumped to the OutputStream of the response. However, does calling getContentLength() also result in the actual file data somehow partially or fully being downloaded? In other words, when i invoke conn.getContentLength(), how much of the file will be returned from the server? Does the headers come "separate" from the content?

All input highly appreciated!


However, does calling getContentLength() also result in the actual file data somehow partially or fully being downloaded?

No, the getContentLength() method just returns a String value of the size of the content as an Integer.

In other words, when i invoke conn.getContentLength(), how much of the file will be returned from the server?

None of the file will be downloaded.

Does the headers come "separate" from the content?

Yes, the headers come "separate" from the content.

Now you're certain :D


See the javadocs

Returns the value of the content-length header field.

So a call to getContentLength() merely reads the header value and does not cause any downloading. You have to call getContent() for that.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜