java如何获取http返回的302或301信息中的跳转网址呢?
下文笔者讲述获取http返回的302或301信息中的跳转网址的方法分享,如下所示
实现思路:
使用getHeaderField("Location")
即可获取跳转后的网址
例:
public static String get302PageUrl(String link) throws IOException{
URL url = new URL(link);
URLConnection conn = url.openConnection();
System.out.println(conn.getHeaderFields().toString());
String statusCode = conn.getHeaderField(0);
//{null=[HTTP/1.1 302 Found], Server=[BWS/1.1], X-Ua-Compatible=[IE=Edge,chrome=1], Connection=[Keep-Alive],
// Pragma=[no-cache], Date=[Thu, 15 Jul 2022 10:31:38 GMT], Cache-Control=[no-cache, must-revalidate],
// X-Xss-Protection=[1;mode=block], Bdpagetype=[3], Set-Cookie=[BDSVRTM=0; path=/],
// Expires=[Fri, 01 Jan 1990 00:00:00 GMT], Content-Length=[225],
// Location=[https://www.java265.com/*******.html],
// Content-Type=[text/html;charset=utf8]}
if(statusCode.indexOf("301")!=-1 || statusCode.indexOf("302")!=-1){
return conn.getHeaderField("Location");
}
return link;
}
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。


