Java 获取网络302重定向URL的方法
方法1:
importjava.net.HttpURLConnection;
importjava.net.URL;
importorg.junit.Assert;
importorg.junit.Test;
publicclassGetRedirectUrlTest{
@Test
publicvoidtest_getRedirectUrl()throwsException{
Stringurl="http://www.baidu.com/link?url=ByBJLpHsj5nXx6DESXbmMjIrU5W4Eh0yg5wCQpe3kCQMlJK_RJBmdEYGm0DDTCoTDGaz7rH80gxjvtvoqJuYxK";
StringexpectUrl="http://www.zhihu.com/question/20583607/answer/16597802";
StringredictURL=getRedirectUrl(url);
Assert.assertEquals(expectUrl,redictURL);
}
/**
*获取重定向地址
*@parampath
*@return
*@throwsException
*/
privateStringgetRedirectUrl(Stringpath)throwsException{
HttpURLConnectionconn=(HttpURLConnection)newURL(path)
.openConnection();
conn.setInstanceFollowRedirects(false);
conn.setConnectTimeout(5000);
returnconn.getHeaderField("Location");
}
}
方法2:
/**
*处理跳转链接,获取重定向地址
*@paramurl源地址
*@return目标网页的绝对地址
*/
publicStringgetAbsUrl(Stringurl){
CloseableHttpClienthttpclient=HttpClients.createDefault();
HttpClientContextcontext=HttpClientContext.create();
HttpGethttpget=newHttpGet(url);
CloseableHttpResponseresponse=null;
StringabsUrl=null;
try{
response=httpclient.execute(httpget,context);
HttpHosttarget=context.getTargetHost();
ListredirectLocations=context.getRedirectLocations();
URIlocation=URIUtils.resolve(httpget.getURI(),target,redirectLocations);
System.out.println("FinalHTTPlocation:"+location.toASCIIString());
absUrl=location.toASCIIString();
}catch(IOExceptione){
e.printStackTrace();
}catch(URISyntaxExceptione){
e.printStackTrace();
}finally{
try{
httpclient.close();
response.close();
}catch(IOExceptione){
e.printStackTrace();
}
}
returnabsUrl;
}
以上就是2中最常用的方法,感谢大家对毛票票的支持。