URL url = new URL("your url"); HttpURLConnection conn =  (HttpURLConnection)url.openConnection();
conn.connect();
BufferedReader is = new BufferedReader(new InputStreamReader(conn.getInputStream(), "gb2312"));
String content = is.readLine();
while(null != content){
System.out.println(content);
content = is.readLine();
}
conn.disconnect();
当我需要访问另一页面时,我需要重新new url,再open connect??能不能重定向?

解决方案 »

  1.   

    public static void HttpURLConnection.setFollowRedirects(boolean followRedirects)
    public void HttpURLConnection.setInstanceFollowRedirects(boolean followRedirects)
    前者设置所有的http连接是否自动处理重定向;
    后者设置本次连接是否自动处理重定向。
    设置成true,系统自动处理重定向;设置成false,则需要自己从http reply中分析新的url
    自己重新连接。
      

  2.   

    谢谢楼上。那如果我要跳到另一页面,是不是必须new url, 重新open connect呢?
      

  3.   

    如果你所说的另一页,当然要 new URL了。
    因为你的HttpURLConnection对象产生于原URL对象。你既然要跳转到一个不相关的
    完全不同的页面,没有必要也不可能还使用原URL对象。这样,你的URL都要新的,
    该URL的附属品HttpURLConnection对象当然也需要一个新的了。
    URL u1 = new URL("http://www.this.com");
    HttpURLConnection conn1 = (HttpURLConnection)u1.openConnection();
    //do something else with conn1
    URL u2 = new URL("http://www.that.com");
    HttpURLConnection conn2 = (HttpURLConnection)u2.openConnection();
    //do something else with conn2
      

  4.   

    resp.sendRedirect()
    request.getRequestDispatcher().forward()
    都能重定向网页吧?