`
jinyanhui2008
  • 浏览: 312905 次
  • 性别: Icon_minigender_1
  • 来自: 青岛
社区版块
存档分类
最新评论

HttpURLConnection使用中遇到的一个问题

    博客分类:
  • Java
阅读更多

  今天跟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试试,这个程序实现的是一个很简单的网页阅读器呵!

 

{此篇文章转自amigo姐姐的博客}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics