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 2023-07-18 17:34  五官一体即忢  阅读(384)  评论(0)    收藏  举报

导航