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

How to Find Redirected URLs in Java?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-11 21:21:03535browse

How to Find Redirected URLs in Java?

Finding Redirected URLs in Java

While accessing web pages in Java, it's crucial to handle scenarios where URLs redirect to alternate locations. To determine the redirected URL, you can use the URL and URLConnection classes.

Using URLConnection.getUrl()

After establishing a connection using URLConnection, you can retrieve the actual URL the connection redirects to by invoking getUrl(). This provides the redirected URL, as the connection automatically follows redirects by default.

URLConnection con = url.openConnection();
con.connect();
System.out.println("Redirected URL: " + con.getURL());

Checking for Redirection Before Retrieving Content

In certain cases, you may want to know if a URL redirects before fetching its content. To achieve this, follow these steps:

  1. Create an HttpURLConnection instance and set setInstanceFollowRedirects to false.
  2. Establish a connection using connect().
  3. Get the response code using getResponseCode(). If it's a redirect code (e.g., 301, 302), it indicates a redirection.
  4. Retrieve the actual redirected URL using getHeaderField("Location").
HttpURLConnection con = (HttpURLConnection)(new URL( url ).openConnection());
con.setInstanceFollowRedirects( false );
con.connect();
int responseCode = con.getResponseCode();
String location = con.getHeaderField( "Location" );

The above is the detailed content of How to Find 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