使用HttpURLConnection获得重定向地址

今天跟TiGERTiAN谈到HttpURLConnection使用中的一个问题,就是当连接到的那个地址重定向到另一个地址时,怎么样获得那个重定向后的地址,弄了一下,找出了方法,结果起先我们两个都没想到,嘿嘿,在此记录一下。
HttpURLConnection是基于HTTP协议的,其底层通过socket通信实现。
下面来看一个例子:

import java.net.HttpURLConnection;
import java.net.URL;
import java.io.BufferedReader;
import java.io.InputStreamReader;
/** *//**
* 网页阅读器.
* @author <a href="mailto:xiexingxing1121@126.com">AmigoXie</a>
* Creation date: 2007-10-9 - 上午11:47:26
*/
public class PageReader {
//连接对象
private static HttpURLConnection conn;
/** *//**
* 根据url连接某地址,并返回返回码.
* 返回码说明:
* 0~200为正常情况,其中200为OK
* 其余都为错误的情况,具体请参见w3
* @param urlStr 需连接的url字符串
*/
private int connect(String urlStr) throws Exception {
URL url = new URL(urlStr);
conn = (HttpURLConnection) url.openConnection();
System.out.println("返回码: " + conn.getResponseCode());
//如果定向的地址经过重定向,
//那么conn.getURL().toString()显示的是重定向后的地址
System.out.println(conn.getURL().toString());
return conn.getResponseCode();
}
/** *//**
* 读取网页的内容.
* @return 返回网页的内容
*/
private String readContents() throws Exception {
BufferedReader in = null;
StringBuffer sb = new StringBuffer();
in = new BufferedReader(new InputStreamReader(conn
.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
sb.append(inputLine);
sb.append("\n");
}
return sb.toString();
}
/** *//**
* 中断连接.
*/
private void disconnect() {
conn.disconnect();
}
/** *//**
* 测试方法
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
PageReader reader = new PageReader();
String url = "http://hexapixel.com/download.php?file=com.hexapixel.widgets.ribbon.alphatest.src.jar";
reader.connect(url);
String content = reader.readContents();
System.out.println("网页内容:" + content);
reader.disconnect();
}
}
呵呵,http://hexapixel.com/download.php?file=com.hexapixel.widgets.ribbon.alphatest.src.jar
这个地址会进行重定向,定向为:http://hexapixel.com/files/com.hexapixel.widgets.ribbon.alphatest.src.jar
TiGERTiAN想要获得的就是后面那个地址,运行该程序后,大家可以看到,System.out.println(conn.getURL().toString());打出的就是这个地址,可惜TiGERTiAN和我开始都没想到,看来是要多试试的。大家可以将那个url地址改成http://www.blogjava.net/amigoxie试试,这个程序实现的是一个很简单的网页阅读器呵!
1
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值