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" );
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