import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class ShortUrlRedirect {
public static String getFinalRedirectUrl(String shortUrl) throws Exception {
HttpURLConnection.setFollowRedirects(false);
HttpURLConnection con = (HttpURLConnection) new URL(shortUrl).openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("User-Agent", "Mozilla/5.0");
int responseCode = con.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
return shortUrl;
} else if (responseCode == HttpURLConnection.HTTP_MOVED_PERM || responseCode == HttpURLConnection.HTTP_MOVED_TEMP) {
String redirectUrl = con.getHeaderField("Location");
redirectUrl = redirectUrl.replaceAll(" ", "%20");
return getFinalRedirectUrl(redirectUrl);
} else {
return null;
}
}
public static void main(String[] args) throws Exception {
String shortUrl = "https://sourl.cn/c2XJ9j";
String finalUrl = getFinalRedirectUrl(shortUrl);
System.out.println(finalUrl);
}
}
结果: