我正在尝试创建一个代码来获取所需网站的最终重定向 URL,但在处理 http 响应 302 时遇到问题。似乎它没有正确执行请求,否则我不明白出了什么问题。我已经测试了它强制重定向 twitter.com 和 facebook.com 并且效果很好(虽然响应 301),但是当尝试“urlin”中指示的 URL 时,会进入 http 302 响应的无限循环。
这是我的第一篇文章,所以我无法发布打印输出,因为它提供了两个以上的链接。
这是代码:
/**
* @param args
*/
public static void main(String[] args) {
String urlin = "http://feeds.nashuatelegraph.com/~r/news/breaking/~3/jxDTXgSDSGc/jpmorgan-ex-workers-charged-in-london-whale-loss.html";
String url = new String();
try{
System.out.println("URL to redirect: "+urlin);
int iteration = 0;
//Preparamos la conexión
HttpURLConnection con =(HttpURLConnection) new URL(urlin).openConnection();
// con.setRequestProperty("User-Agent", "Mozilla 5.0");
con.setReadTimeout(20000);
con.setInstanceFollowRedirects(false);
//Definimos un booleano que hara de flag
boolean redirect = true;
//Iniciamos la busqueda de URL final
while(redirect){
System.out.println("\nIteration number: "+ ++iteration);
con.connect();
System.out.println("Connected URL: "+con.getURL().toString());
int status = con.getResponseCode();
System.out.println("status: "+status);
//Tratamos el codigo de respuesta obtenido
if (status != HttpURLConnection.HTTP_OK) {
if (status == HttpURLConnection.HTTP_MOVED_TEMP
|| status == HttpURLConnection.HTTP_MOVED_PERM
|| status == HttpURLConnection.HTTP_SEE_OTHER){
redirect = true;
//Capturamos la nueva URL
String newUrl = con.getHeaderField("location");
//Obtenemos la cookie por si se necesita
String cookies = con.getHeaderField("Set-Cookie");
System.out.println("Cookies: "+cookies);
//Reabrimos la conexión
con = (HttpURLConnection) new URL(newUrl).openConnection();
if(cookies!=null){
con.setRequestProperty("Cookie", cookies);
}
}
//Tratamos los errores 400 y 404
if (status == HttpURLConnection.HTTP_NOT_FOUND || status == HttpURLConnection.HTTP_BAD_REQUEST){
throw new Exception("Error 400 o 404");
}
} else {
redirect = false;
//Obtenemos la URL final
url = con.getURL().toString();
}
}
} catch (SocketTimeoutException e) {
System.out.println("Se ha producido un timeout con URL: "+urlin);
} catch (UnknownHostException e) {
System.out.println("Direccion URL desconocida: "+urlin);
e.printStackTrace();
} catch (IOException e) {
System.out.println("Error IOException al procesar el registro URL: "+urlin);
e.printStackTrace();
} catch (Exception e) {
System.out.println("Error al procesar el registro URL: "+urlin);
e.printStackTrace();
}
if(!url.equals("")) {
System.out.println("URL final: "+url);
} else {
System.out.println("URL final: "+urlin);
}
}
我会很感激你能给的所有建议。