Determining the Redirected URL in Java
When accessing web pages using URLConnection, it's common to encounter redirects. This occurs when a URL points to another destination. To determine the redirected URL, we need to understand how HTTP redirects work.
Typically, a server responds with a 3xx status code (e.g., 301, 302) indicating a redirect. The response includes a "Location" header field specifying the new destination. However, the URLConnection does not automatically follow redirects.
Accessing the Redirected URL
To obtain the redirected URL, we can manually invoke getInputStream() on the URLConnection after initial connection. This action forces the connection establishment, and the server sends the final response, including the "Location" header.
URLConnection con = new URL(url).openConnection(); con.connect(); System.out.println("Original URL: " + con.getURL()); InputStream is = con.getInputStream(); System.out.println("Redirected URL: " + con.getURL()); is.close();
Accessing the Location Header
In some cases, we may want to access the "Location" header before fetching the redirected content. For this purpose, we can use HttpURLConnection and set setInstanceFollowRedirects(false):
HttpURLConnection con = (HttpURLConnection) (new URL(url).openConnection()); con.setInstanceFollowRedirects(false); con.connect(); System.out.println("Response code: " + con.getResponseCode()); String location = con.getHeaderField("Location"); System.out.println("Location header: " + location);
The above is the detailed content of How to Determine the Redirected URL in Java?. For more information, please follow other related articles on the PHP Chinese website!