开发者

URLConnection and content length : how much data is download?

开发者 https://www.devze.com 2023-03-30 18:41 出处:网络
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:

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

精彩评论

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