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 1st 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 1st December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW

1. Introduction

Understanding how URLs are redirected is crucial in web development and network programming tasks, such as handling HTTP redirects, validating URL redirects, or extracting final destination URLs. In Java, we can accomplish this functionality using HttpURLConnection or HttpClient libraries.

In this tutorial, we’ll explore different approaches to finding the redirected URL of a given URL in Java.

2. Using HttpURLConnection

Java provides the HttpURLConnection class, which allows us to make HTTP requests and handle responses. Also, we can make use of the HttpURLConnection to find the redirected URL of a given URL. Here’s how it can be done:

String canonicalUrl = "http://www.baeldung.com/";
String expectedRedirectedUrl = "https://www.baeldung.com/";

@Test
public void givenOriginalUrl_whenFindRedirectUrlUsingHttpURLConnection_thenCorrectRedirectedUrlReturned() throws IOException {
    URL url = new URL(canonicalUrl);
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setInstanceFollowRedirects(true);
    int status = connection.getResponseCode();
    String redirectedUrl = null;
    if (status == HttpURLConnection.HTTP_MOVED_PERM || status == HttpURLConnection.HTTP_MOVED_TEMP) {
        redirectedUrl = connection.getHeaderField("Location");
    }
    connection.disconnect();
    assertEquals(expectedRedirectedUrl, redirectedUrl);
}

Here, we define the original URL string (canonicalUrl) and the redirected URL (expectedRedirectedUrl). Then, we create an HttpURLConnection object and open a connection to the original URL.

Afterward, we set the instanceFollowRedirects property to true to enable automatic redirection. Upon receiving the response, we examine the status code to determine if redirection occurred. If redirection occurs, we retrieve the redirected URL from the “Location” header.

Finally, we disconnect the connection and assert that the retrieved redirected URL matches the expected one.

3. Using Apache HttpClient

Alternatively, we can use Apache HttpClient, a more versatile HTTP client library for Java. Apache HttpClient provides more advanced features and better support for handling HTTP requests and responses. Here’s how we can find the redirected URL using Apache HttpClient:

@Test
public void givenOriginalUrl_whenFindRedirectUrlUsingHttpClient_thenCorrectRedirectedUrlReturned() throws IOException {
    RequestConfig config = RequestConfig.custom()
      .setRedirectsEnabled(false)
      .build();
    try (CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(config).build()) {
        HttpGet httpGet = new HttpGet(canonicalUrl);
        try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
            int statusCode = response.getStatusLine().getStatusCode();
            String redirectedUrl = null;
            if (statusCode == HttpURLConnection.HTTP_MOVED_PERM || statusCode == HttpURLConnection.HTTP_MOVED_TEMP) {
                org.apache.http.Header[] headers = response.getHeaders("Location");
                if (headers.length > 0) {
                    redirectedUrl = headers[0].getValue();
                }
            }
            assertEquals(expectedRedirectedUrl, redirectedUrl);
        }
    }
}

In this test, we begin by configuring the request to deactivate automatic redirection. Subsequently, we instantiate a CloseableHttpClient and dispatch an HttpGet request to the original URL.

Upon obtaining the response, we analyze the status code and headers to ascertain whether redirection occurred. In the event of redirection, we extract the redirected URL from the Location header.

4. Conclusion

In this article, we discussed how handling redirection correctly is essential for building robust web applications that interact with external resources. We’ve explored how to find the redirected URL of a given URL using both HttpURLConnection and Apache HttpClient.

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 1st 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 1st December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW

1 Comment
Oldest
Newest