You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何利用java.net.URLConnection通过GET请求获取重定向URL?

How to Get the Redirected URL with java.net.URLConnection

Got it, let's walk through exactly how to grab the new URL when your GET request gets redirected using java.net.URLConnection. There are two main scenarios depending on whether you want the connection to automatically follow redirects or not.

1. When allowing automatic redirects (default behavior)

By default, URLConnection automatically follows up to 5 redirects. Once it finishes processing all redirects, you can get the final destination URL directly using the getURL() method of the connection object—this method updates to point to the last URL in the redirect chain.

Here's a quick code example:

import java.net.URL;
import java.net.URLConnection;
import java.io.IOException;

public class RedirectExample {
    public static void main(String[] args) throws IOException {
        String originalUrl = "https://example.com/redirecting-page";
        URL url = new URL(originalUrl);
        URLConnection connection = url.openConnection();
        
        // Trigger the request (calling getResponseCode() forces the connection to send the request)
        int responseCode = connection.getResponseCode();
        
        // Get the final redirected URL
        URL finalUrl = connection.getURL();
        System.out.println("Final redirected URL: " + finalUrl.toString());
    }
}

Note: You need to trigger the request first (via methods like getResponseCode() or reading the input stream) before getURL() will return the final redirected address—until then, it still points to the original URL.

2. When disabling automatic redirects (manual handling)

If you want to handle redirects yourself (e.g., log each step or modify headers before following), disable automatic redirects with setInstanceFollowRedirects(false). Then extract the Location header from the response, which contains the target URL for the redirect.

Keep these details in mind:

  • Redirects will return a 3xx status code (like 301 Moved Permanently, 302 Found).
  • The Location header might be a relative URL, so you need to resolve it against the original URL to get the absolute path.

Here's how to implement this:

import java.net.URL;
import java.net.URLConnection;
import java.io.IOException;

public class ManualRedirectExample {
    public static void main(String[] args) throws IOException {
        String originalUrl = "https://example.com/redirecting-page";
        URL url = new URL(originalUrl);
        URLConnection connection = url.openConnection();
        
        // Disable automatic redirects
        connection.setInstanceFollowRedirects(false);
        
        int responseCode = connection.getResponseCode();
        
        // Check if we're dealing with a redirect
        if (responseCode >= 300 && responseCode < 400) {
            String locationHeader = connection.getHeaderField("Location");
            
            // Resolve relative URL to absolute path using the original URL
            URL redirectedUrl = new URL(url, locationHeader);
            System.out.println("Redirected to: " + redirectedUrl.toString());
            
            // If you want to follow the redirect manually, open a new connection here
            // URLConnection newConnection = redirectedUrl.openConnection();
        } else {
            System.out.println("No redirect occurred.");
        }
    }
}

Key Tips

  • Always validate the response code first when handling redirects manually—this ensures you only process Location headers when a redirect is actually happening.
  • The Location header is case-insensitive, but using "Location" as the header name works reliably across most servers.
  • For HTTPS URLs, HttpsURLConnection (a subclass of URLConnection) works exactly the same way—all the above methods apply to it too.

内容的提问来源于stack exchange,提问作者Tim Nuwin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 07:42:23