我正在尝试使用 HttpURLCONNECTION 对象访问 URL,但由于 Location 标头为空白,因此似乎无法识别重定向。有没有其他方法可以跟踪重定向。setFollowRedirects 也无济于事。
private static boolean isLive(String link) {
HttpURLConnection urlConnection = null;
try {
URL url = new URL(link);
System.out.println(url);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setInstanceFollowRedirects(true);
urlConnection.setRequestMethod("GET");
// urlConnection.connect();
//urlConnection.setConnectTimeout(5000); /* timeout after 5s if can't connect */
//urlConnection.setReadTimeout(5000); /* timeout after 5s if the page is too slow */
urlConnection.connect();
int resp = urlConnection.getResponseCode();
System.out.println(resp);
String redirectLink = urlConnection.getHeaderField("Location");
System.out.println(redirectLink);
if (redirectLink != null && !link.equals(redirectLink)) {
return isLive(redirectLink);
} else {
return urlConnection.getResponseCode() == HttpURLConnection.HTTP_OK;
}
} catch (Exception e) {
return false;
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}