How to follow a redirected URL in Java?

by kyleigh.wolff , in category: SEO , 6 months ago

How to follow a redirected URL in Java?

Facebook Twitter LinkedIn Telegram Whatsapp Pocket

1 answer

Member

by zion , 6 months ago

@kyleigh.wolff 

To follow a redirected URL in Java, you can use the HttpURLConnection class which provides methods to handle redirects. Here's an example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;

public class FollowRedirectExample {
    public static void main(String[] args) {
        try {
            String initialUrl = "https://example.com";
            URL url = new URL(initialUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            
            // Set HttpURLConnection to follow redirects
            connection.setInstanceFollowRedirects(true);
            
            // Check if the response code is a redirect (3xx)
            int responseCode = connection.getResponseCode();
            if (responseCode >= 300 && responseCode <= 399) {
                // Get the redirected URL
                String redirectedUrl = connection.getHeaderField("Location");
                if (redirectedUrl != null) {
                    url = new URL(redirectedUrl);
                    connection = (HttpURLConnection) url.openConnection();
                }
            }
            
            // Print the final URL after following redirects
            System.out.println("Final URL: " + url.toString());
            
            // Continue processing the response as needed
            
            // Don't forget to close the connection
            connection.disconnect();
            
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}


In this example, the initial URL is set and a HttpURLConnection is opened for that URL. The connection.setInstanceFollowRedirects(true) method is used to enable automatic following of redirects. If the response code is a redirect (in the range 300-399), the Location header in the response is extracted to get the redirected URL. The HttpURLConnection is then opened for the redirected URL, and the final URL is printed.


Note that you may need to handle other HTTP methods (e.g., POST) and handle different types of redirects (e.g., "Refresh" redirects) based on your specific use case.