JAVA获取重定向之后的url
问题描述
有一个url短链,在访问中这个短链的时候,会重定向到另外一个目标地址。需要通过JAVA代码根据短链获取重定向之后的地址。
处理方案
import java.net.HttpURLConnection;
import java.net.URL;
/**
* 获取重定向地址
* @param path
* @return
* @throws Exception
*/
private String getRedirectURL(String path) throws Exception {
HttpURLConnection conn = (HttpURLConnection) new URL(path).openConnection();
conn.setInstanceFollowRedirects(false);
conn.setConnectTimeout(5000);
return conn.getHeaderField("location");
}
通过HttpURLConnection响应头中的location可以取到重定向地址。
最终效果图