Home > Java > javaTutorial > body text

How to Determine the Redirected URL in Java?

Mary-Kate Olsen
Release: 2024-11-11 12:33:03
Original
219 people have browsed it

How to Determine the Redirected URL in Java?

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();
Copy after login

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);
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template