Partner – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

Course – Black Friday 2026 – NPI EA – main – before_post_content
announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 4th December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW

Course – Black Friday 2026 – NPI – main – before_post_content
announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 4th December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW

1. Overview

The HTTP protocol provides comprehensive information about requested web resources. One of its header fields, Content-Length, specifies the size of a resource in bytes. We can extract this information using the URLConnection class.

Knowing the size of a web file before downloading helps estimate the amount of network data required to download the resource.

In this tutorial, we’ll explore how to get the size of a web file using the getContentLengthLong() and getHeaderField() methods of the URLConnection class.

2. HTTP Content-Length

The Content-Length attribute specifies the size of a web file in the HTTP headers. Since HTTP is a transfer protocol, it provides details of an incoming response. Simply put, the Content-Length field represents the size of the response body in bytes.

Furthermore, the Transfer-Encoding field can be specified and set to chunked instead of the Content-Length field. In this case, we can’t determine the size of the web file as the download is done in chunks.

Notably, the Content-Length header isn’t always accurate. Servers can set this field to any arbitrary value, which may not represent the true file size. For example, when using ResponseEntity in a Spring application, a developer can set the header field to any value, which may not correspond to the actual size of the response body.

3. The getContentLength() and getContentLengthLong() Methods

The URLConnection class in Java provides methods to establish connections with URL resources for write or read operations.

It provides a method named getContentLength() that returns the content length of the HTTP header field as an integer. However, this method can’t represent numbers greater than Integer.MAX_VALUE, which means it cannot handle file sizes greater than 2 GiB.

To address the limitation of the getContentLength() method, the URLConnection class provides the getContentLengthLong() method, which returns the content length as a long value. This method is preferable as it can retrieve large file sizes that exceed Integer.MAX_VALUE.

Notably, the getContentLength() and getContentLengthLong() methods return -1 when the Content-Length field is missing from the HTTP headers.

4. Using the getContentLengthLong() Method

Let’s see an example that retrieves a dummy PDF file size from “https://www.ingka.com/wp-content/uploads/2020/11/dummy.pdf“.

First, let’s define a URL instance that represents the URL to the web file:

String fileUrl = "https://www.ingka.com/wp-content/uploads/2020/11/dummy.pdf";
URL url = new URL(fileUrl);

Next, let’s create a URLConnection object and open a connection to this URL:

URLConnection urlConnection = url.openConnection();

Then, let’s get the size of the web file:

long fileSize = urlConnection.getContentLengthLong();
if (fileSize != -1) {
    assertEquals(29789, fileSize);
} else {
    fail("Could not determine file size");
}

In the code above, we invoke the getContentLengthLong() method on the urlConnection object to get an estimated file size. Then, we assert that the estimated file size equals the expected size.

Also, we handle the case where a web file size couldn’t determine the web file size.

5. Using the getHeaderField() Method

Alternatively, we can use the getHeaderField() method to retrieve the web file size. The method returns the name field value it accepts as an argument.

Here’s an example that uses the getHeaderField() method:

@Test
void givenUrl_whenGetFileSizeUsingURLConnectionAndGetHeaderField_thenCorrect() throws IOException {
    URL url = new URL(fileUrl);
    URLConnection urlConnection = url.openConnection();

    String headerField = urlConnection.getHeaderField("Content-Length");
    if (headerField != null && !headerField.isEmpty()) {
        long fileSize = Long.parseLong(headerField);
        assertEquals(29789, fileSize);
    } else {
        fail("Could not determine file size");
    }
}

In the code above, we invoke the getHeaderField() method on the URLConnection object and specify the Content-Length header field. Since the method returns a string, we parse its value to a long type and assert that the return size is equal to the expected size.

6. Conclusion

In this tutorial, we saw how to use the URLConnection.getContentLengthLong() and URLConnection.getHeaderField() methods to retrieve the size of a known web file. We leverage the Content-Length field of the HTTP header to determine the web file size. When the file size can’t be determined, it returns a value of negative one (-1).

The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.
Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

Course – Black Friday 2026 – NPI EA – main – after_post_content

announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 4th December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW

Course – Black Friday 2026 – NPI – main – after_post_content

announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 4th December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW