首页  ·  知识 ·  编程语言
使用HttpURLConnection获得重定向地址
阿蜜果  http://publish.itpub.net/  Java  编辑:dezai  图片来源:网络
HttpURLConnection是基于HTTP协议的,其底层通过socket
HttpURLConnection是基于HTTP协议的,其底层通过socket通信实现。
      下面来看一个例子:

import java.net.HttpURLConnection; import java.net.URL; import java.io.BufferedReader; import java.io.InputStreamReader; /** *//** * 网页阅读器. * @author AmigoXie * 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试试,这个程序实现的是一个很简单的网页阅读器呵! 本文作者:阿蜜果 来源:http://publish.itpub.net/
CIO之家 www.ciozj.com 微信公众号:imciow
   
免责声明:本站转载此文章旨在分享信息,不代表对其内容的完全认同。文章来源已尽可能注明,若涉及版权问题,请及时与我们联系,我们将积极配合处理。同时,我们无法对文章内容的真实性、准确性及完整性进行完全保证,对于因文章内容而产生的任何后果,本账号不承担法律责任。转载仅出于传播目的,读者应自行对内容进行核实与判断。请谨慎参考文章信息,一切责任由读者自行承担。
延伸阅读