Java根据原始URL获取网络重定向后的URL

方法1:

复制代码
 /**
      * 获取重定向地址
      * @param path 原地址
      * @return
      * @throws Exception
      */
     private String getRedirectUrl(String path) throws Exception {
         HttpURLConnection conn = (HttpURLConnection) new URL(path)
                 .openConnection();
         conn.setInstanceFollowRedirects(false);
         conn.setConnectTimeout(5000);
         return conn.getHeaderField("Location");
     }
 }
复制代码

方法2:

复制代码
/**
       * 处理跳转链接,获取重定向地址
       * @param url   源地址
       * @return      目标网页的绝对地址
       */
      public String getAbsUrl(String url){
          CloseableHttpClient httpclient = HttpClients.createDefault();
          HttpClientContext context = HttpClientContext.create();
          HttpGet httpget = new HttpGet(url);
         CloseableHttpResponse response = null;
         String absUrl = null;
         try {
             response = httpclient.execute(httpget, context);
             HttpHost target = context.getTargetHost();
             List<URI> redirectLocations = context.getRedirectLocations();
             URI location = URIUtils.resolve(httpget.getURI(), target, redirectLocations);
             System.out.println("Final HTTP location: " + location.toASCIIString());
             absUrl = location.toASCIIString();          
         }catch(IOException e){
             e.printStackTrace();
         }catch (URISyntaxException e) {         
             e.printStackTrace();
         }finally {
             try {
                 httpclient.close();
                 response.close();
             } catch (IOException e) {               
                 e.printStackTrace();
             }
         }
         return absUrl;
     }
复制代码

 

posted on   五官一体即忢  阅读(333)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· DeepSeek 开源周回顾「GitHub 热点速览」
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

导航

统计

点击右上角即可分享
微信分享提示