Java 获取网络重定向URL(302重定向)

方法1:

 1 import java.net.HttpURLConnection;
 2 import java.net.URL;
 3  
 4 import org.junit.Assert;
 5 import org.junit.Test;
 6  
 7 public class GetRedirectUrlTest {
 8     @Test
 9     public void test_getRedirectUrl() throws Exception {
10         String url="http://www.baidu.com/link?url=ByBJLpHsj5nXx6DESXbmMjIrU5W4Eh0yg5wCQpe3kCQMlJK_RJBmdEYGm0DDTCoTDGaz7rH80gxjvtvoqJuYxK";
11         String expectUrl="http://www.zhihu.com/question/20583607/answer/16597802";
12         String redictURL = getRedirectUrl(url);
13         Assert.assertEquals(expectUrl, redictURL);
14     }
15     
16     /**
17      * 获取重定向地址
18      * @param path
19      * @return
20      * @throws Exception
21      */
22     private String getRedirectUrl(String path) throws Exception {
23         HttpURLConnection conn = (HttpURLConnection) new URL(path)
24                 .openConnection();
25         conn.setInstanceFollowRedirects(false);
26         conn.setConnectTimeout(5000);
27         return conn.getHeaderField("Location");
28     }
29 }

 

方法2:

 1 /**
 2      * 处理跳转链接,获取重定向地址
 3      * @param url   源地址
 4      * @return      目标网页的绝对地址
 5      */
 6     public String getAbsUrl(String url){
 7         CloseableHttpClient httpclient = HttpClients.createDefault();
 8         HttpClientContext context = HttpClientContext.create();
 9         HttpGet httpget = new HttpGet(url);
10         CloseableHttpResponse response = null;
11         String absUrl = null;
12         try {
13             response = httpclient.execute(httpget, context);
14             HttpHost target = context.getTargetHost();
15             List<URI> redirectLocations = context.getRedirectLocations();
16             URI location = URIUtils.resolve(httpget.getURI(), target, redirectLocations);
17             System.out.println("Final HTTP location: " + location.toASCIIString());
18             absUrl = location.toASCIIString();          
19         }catch(IOException e){
20             e.printStackTrace();
21         }catch (URISyntaxException e) {         
22             e.printStackTrace();
23         }finally {
24             try {
25                 httpclient.close();
26                 response.close();
27             } catch (IOException e) {               
28                 e.printStackTrace();
29             }
30         }
31         return absUrl;
32     }

 

转载于:https://www.cnblogs.com/fnlingnzb-learner/p/11429834.html

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值