很多网站都使用了URL重定向技术,把一个原始请求从一个位置路由到另一个位置。原因可能是多方面的,比如域名转发、URL缩写、隐私保护、在同一网站维持相似的域名等。
本文讲述怎样使用Apache HTTPComponents HttpClient实现URL重定向。
本文使用的工具:
1. Apache HttpComponents Client 4.3.1
2. JDK 1.7
1、创建Java项目
项目我命名为HttpClientTest,导入如下JAR包:

2、开发
1)创建和配置CloseableHttpClient
CloseableHttpClient是线程安全的,单个实例可用于处理多个HTTP请求。Http Client会自动处理所有的重定向,除非明确地使用disableAutomaticRetries()关闭自动重定向。
2)使用链接创建HttpGet实例,获取重定向。
3)创建本地HTTP执行上下文HttpClientContext。
4)使用Http Client并传递本地实例HttpClientContext,执行HttpGet请求。
5)成功执行请求后,使用上下文对象来获取所有的重定向位置。
6)关闭响应CloseableHttpResponse,释放资源。

package com.ch.net; 

import java.io.IOException;
import java.net.URI;
import java.util.List; import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients; public class UrlRedirectionDemo {
// 浏览器Agent
public static String USER_AGENT = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_3) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.151 Safari/535.19"; // 创建并配置HttpClient
private static final CloseableHttpClient httpClient = HttpClients
.custom()
.setUserAgent(USER_AGENT)
.setDefaultRequestConfig(
RequestConfig.custom()
.setCookieSpec(CookieSpecs.BROWSER_COMPATIBILITY)
.build()).build(); /**
* 根据给定的链接获取所有的重定向位置
* @param link 给定的链接
* @return
* @throws ClientProtocolException
* @throws IOException
*/
public List<URI> getAllRedirectLocations(String link) throws ClientProtocolException, IOException{
List<URI> redirectLocations = null;
CloseableHttpResponse response = null;
try{
HttpClientContext context = HttpClientContext.create();
HttpGet httpGet = new HttpGet(link);
response = httpClient.execute(httpGet, context); // 获取所有的重定向位置
redirectLocations = context.getRedirectLocations();
} finally{
if(response!=null){
response.close();
}
}
return redirectLocations;
} public static void main(String[] args) throws ClientProtocolException, IOException{
// 输入URL
String link = "http://t.cn/zjYwrl3";
UrlRedirectionDemo demo = new UrlRedirectionDemo();
List<URI> allRedirectLocations = demo.getAllRedirectLocations(link);
if(allRedirectLocations!=null){
System.out.println(link);
for(URI uri : allRedirectLocations){
System.out.println("|\nv\n" + uri.toASCIIString());
}
} else{
System.out.println("Not found!");
}
}
}
 

如果使用默认的User-Agent设置,有些网站会返回HTTP 500状态码错误。一旦网站返回200状态码而且返回的HTML的内容是“500 server error”时,为保证兼容性,应该使用标准的Web浏览器的User-Agent字符串。
500 – 服务器内部错误
200 - 服务器成功返回网页
3、运行
我在新浪微博中找了个URL缩短的地址作为输入,执行后,果然找到了重定向地址。
控制台输出为:

http://t.cn/zjYwrl3
|
v
http://hero.pongo.cn/
 

4、验证
用在线URL重定向检测工具测试:


验证OK。

最新文章

  1. C#测试题
  2. Myeclipse无法开启Servers视图解决办法
  3. DEDE建站之图片标签技巧指南
  4. asp.net使用My97 Date Picker时设置默认起始时间为n年之前的今天
  5. 网络安全之PHP安全编程建议
  6. win7 下配置resin的一些tip
  7. jQuery常用事件详解
  8. Dima and Salad(完全背包)
  9. laravel post请求失败
  10. vue二、脚手架搭建
  11. odoo:开源 ERP/CRM 入门与实践
  12. python while and for
  13. C#抽象类跟接口
  14. plsql developer 使用sys用户登录,报ORA-01031权限不足,解决sys(dba权限用户)远程登录报错。
  15. Android Interpolator(插值器)
  16. InvokeRepeating重复定时器
  17. ASP.NET MVC:4 Ways To Prevent Duplicate Form Submission(转载)
  18. Delphi中ClientDataSet的用法小结
  19. LoadRunner中的随机数
  20. c++语言第二次作业

热门文章

  1. AtomicInteger源码分析——基于CAS的乐观锁实现
  2. java并发库 Lock 公平锁和非公平锁
  3. Swap Nodes &amp; Reverse Nodes in k-Group
  4. windows下安装coreseek/sphinx
  5. codeforces A. Candy Bags 解题报告
  6. [Android UI] ProgressBar自定义
  7. FragmentTabHost+ViewPager实现底部按钮
  8. Android之ViewDragHelper
  9. grep -n 显示行号
  10. 百度编辑器 ueditor .net开发