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中最常用的方法,感谢大家对毛票票的支持。
热门推荐
10 儿子立冬祝福语简短独特
11 对当兵的祝福语简短
12 侄儿高考试祝福语简短
13 伴郎红包祝福语朋友简短
14 媳妇生日简短祝福语朋友
15 公司年会祝福语简短最好
16 元旦感恩祝福语简短大全
17 红包祝福语简短10字
18 周六早晨祝福语简短