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 @   Boblim  阅读(12355)  评论(1编辑  收藏  举报
编辑推荐:
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
阅读排行:
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 单元测试从入门到精通
点击右上角即可分享
微信分享提示