How to Determine Redirected URLs in Java
In Java, when using URLConnection to access web pages, you may encounter scenarios where an initial URL redirects to a different location. Determining the redirected URL can be crucial for further processing or analysis.
This article investigates methods for obtaining the redirected URL from header field information and presents a standard approach using URLConnection.
Getting the Redirected URL from Header Fields
Previously, you extracted the redirected URL from the Set-Cookie header field, which is not a standard method. However, accessing the Location header field can provide a reliable way to find the redirected URL.
Standard Approach Using URLConnection
URLConnection con = new URL(url).openConnection(); con.connect(); InputStream is = con.getInputStream(); System.out.println("Redirected URL: " + con.getURL()); is.close();
Determining Redirection Before Getting Contents
If you need to know about the redirection before getting the contents, 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 Determine Redirected URLs in Java: Standard Approach and Pre-Content Check?. For more information, please follow other related articles on the PHP Chinese website!