java获取重定向url
这里用到了HttpUrlConnection的**setInstanceFollowRedirects()
对重定向进行处理,并用
getHeaderField(“Location”)**得到header的location属性值,及重定向的url。
/**
* 获取重定向地址
* @param path
* @return
* @throws Exception
public static String getRedirectUrl(String path) throws Exception {
HttpURLConnection conn = (HttpURLConnection) new URL(path)
.openConnection();
//设置为不对http链接进行重定向处理
conn.setInstanceFollowRedirects(false);
conn.setConnectTimeout(5000);
//得到请求头的所有属性和值
Map<String, List<String>> map = conn.getHeaderFields();
Set<String> stringSet = map.keySet();
for (String str: stringSet){
System.out.println(str + "------" + conn.getHeaderField(str));
//返回重定向的链接(父类UrlConnection的方法)
return conn.getHeaderField("Location");
}
@Test
void contextLoads() throws Exception {
String data = UrlUtils.getRedirectUrl("http://music.163.com/song/media/outer/url?id=1345368792.mp3");
System.out.println(data);
}
输出结果
null------HTTP/1.1 302
X-Via------MusicServer
Cache-Control------no-cache
Server------nginx
X-From-Src------223.73.11.38
Connection------keep-alive
Expires------Thu, 01 Jan 1970 00:00:00 GMT
Content-Length------0
Date------Sat, 04 Apr 2020 09:37:35 GMT
Location------http://m10.music.126.net/20200404180235/e51d518ebc021f43209d009affd267d1/ymusic/5ef3/c656/6c13/7f16221fbad7c7eba8cf1bf3f3af17e7.mp3
http://m10.music.126.net/20200404180235/e51d518ebc021f43209d009affd267d1/ymusic/5ef3/c656/6c13/7f16221fbad7c7eba8cf1bf3f3af17e7.mp3
参考文档
Java 获取网络重定向URL