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 –

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(
                        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: In actual production use, however, HTTPS URLs are handled by using the actual certificates installed with the product.


2 thoughts on “How to read the file size of a document served at an HTTP/S URL using Java

Speak your mind!

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s