Home > Java > javaTutorial > body text

How to Determine Redirected URLs in Java: Standard Approach and Pre-Content Check?

Linda Hamilton
Release: 2024-11-07 07:52:02
Original
369 people have browsed it

How to Determine Redirected URLs in Java: Standard Approach and Pre-Content Check?

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

  1. Create a URLConnection instance using the original URL.
  2. Connect to the URL using connect().
  3. After connecting, access the contents using getInputStream().
  4. After retrieving the contents, call getURL() on the URLConnection to get the final, redirected URL.
URLConnection con = new URL(url).openConnection();
con.connect();
InputStream is = con.getInputStream();
System.out.println("Redirected URL: " + con.getURL());
is.close();
Copy after login

Determining Redirection Before Getting Contents

If you need to know about the redirection before getting the contents, follow these steps:

  1. Create an HttpURLConnection instance.
  2. Set setInstanceFollowRedirects(false) to prevent automatic redirects.
  3. Connect to the URL using connect().
  4. Check the response code (getResponseCode()) to know if a redirect occurred.
  5. If a redirect occurred, get the new location using getHeaderField("Location").
HttpURLConnection con = (HttpURLConnection)(new URL(url).openConnection());
con.setInstanceFollowRedirects(false);
con.connect();
int responseCode = con.getResponseCode();
String location = con.getHeaderField("Location");
Copy after login

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!

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!