Home >Java >javaTutorial >How to Retrieve Redirected URLs in Java?

How to Retrieve Redirected URLs in Java?

Susan Sarandon
Susan SarandonOriginal
2024-11-08 11:16:02252browse

How to Retrieve Redirected URLs in Java?

Java URL Redirection Retrieval

When accessing web pages through Java's URLConnection, it's essential to handle URL redirections. To obtain the redirected URL, standard techniques exist beyond relying solely on header fields like "Set-Cookie".

The primary method to determine the redirected URL is to call getUrl() on the URLConnection instance after establishing the connection:

URLConnection con = new URL(url).openConnection();

// Connect to the URL
con.connect();

// Obtain the redirected URL
URL redirectedURL = con.getURL();

This mechanism accurately captures the redirected URL irrespective of intermediate responses or missing "Location" header fields.

For instances where you need to verify redirection before fetching the content, the following approach is recommended:

HttpURLConnection con = (HttpURLConnection)(new URL(url).openConnection());

// Deactivate automatic redirection following
con.setInstanceFollowRedirects(false);

// Establish the connection
con.connect();

// Retrieve the response code
int responseCode = con.getResponseCode();

// Examine the response code for redirection
if (responseCode == HttpURLConnection.HTTP_MOVED_TEMP ||
    responseCode == HttpURLConnection.HTTP_MOVED_PERM ||
    responseCode == HttpURLConnection.HTTP_SEE_OTHER) {
    
    // Fetch the "Location" header field
    String location = con.getHeaderField("Location");
    
    // Print the redirected URL
    System.out.println(location);
}

These methods provide reliable mechanisms for handling URL redirections in Java, ensuring accurate URL information during web navigation.

The above is the detailed content of How to Retrieve Redirected URLs in Java?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn