Java obtain network redirection URL (302 redirect)

method 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 }

 

Method 2:

1  / * 
2       * process jumps links for the redirection address
 . 3       * @param URL address source
 . 4       * @return       absolute address of the target page
 . 5       * / 
. 6      public String getAbsUrl (String URL) {
 . 7          CloseableHttpClient HttpClient = HttpClients.createDefault ();
 . 8          HttpClientContext context = HttpClientContext.create ();
 . 9          HttpGet httpget = new 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     }

 

Guess you like

Origin www.cnblogs.com/fnlingnzb-learner/p/11429834.html