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     }

 

posted @ 2019-08-29 15:12  Boblim  阅读(12282)  评论(1编辑  收藏  举报