How to read the file size of a document served at an HTTP/S URL using Java
Recently I was assigned some work where I had to read reports from a custom HTTP (development) or HTTPS (production) URL and e-mail them accordingly, attaching the report to the e-mail if it did not exceed the user configured maximum SMTP attachment size.
The problem I had was that even though the reports were actually stored on the web server’s local file system, I did not have access or permission to access the reports from the file system. All I had was the web URL of the report document. Thus I had no choice but to read the file size somehow from the URL , check it against the configured maximum SMTP attachment size and then e-mail the report. The prototype that I developed is posted at this location – http://pastebin.com/KnsUuAhG
As can be seen, I have used JavaMail for the actual e-mail dispatch. The interesting bit is in the isAttachmentSmallerThanMaxSmtpSize method:
private static boolean isAttachmentSmallerThanMaxSmtpSize(
String attachmentLink) {
boolean status = false;
try {
HttpURLConnection connection = (HttpURLConnection) new URL(
attachmentLink).openConnection();
int sizeInMB = connection.getContentLength() / (1024 * 1024);
if (sizeInMB > MAX_SMTP_SIZE) {
status = false;
} else {
status = true;
}
} catch (Exception ex) {
status = false;
}
return status;
}
where the actual file size can be obtained by simply obtaining the content length of the HTTP (or HTTPS) Connection object.
For my prototype, for HTTPS connections, I actually disabled the HTTPS certificate check by using the method described in this nifty blog: http://www.nakov.com/blog/2009/07/16/disable-certificate-validation-in-java-ssl-connections/. In actual production use, however, HTTPS URLs are handled by using the actual certificates installed with the product.
so a post after 2 years!
Prabhu Kumar
December 7, 2011 at 8:58 pm
Yeah, mate… getting back into the groove at long last
.
z0ltan
December 18, 2011 at 8:39 pm