"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Find Redirected URLs in Java?

How to Find Redirected URLs in Java?

Published on 2024-11-15
Browse:116

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" );
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3