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:
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!