import java.net.*;
import java.io.*;
import java.util.Date;
public class URLdemo { /**
 * @param args
 */
public static void main(String[] args)throws Exception {
// TODO Auto-generated method stub
int c ;
      URL hp = new URL("http://www.osborne.com");
      URLConnection hpcn = hp.openConnection();
      
      System.out.println("Date:"+ new Date(hpcn.getDate()));
      System.out.println("content-type:"+ hpcn.getConnectTimeout());
      
      System.out.println("expires:"+ hpcn.getExpiration());
      System.out.println("last-modeified:"+ new Date(hpcn.getLastModified()));
      int len = hpcn.getContentLength();
      
      System.out.println("length:"+ len);
      if(len > 0)
      {
       System.out.println("===connection====");
       InputStream  input = hpcn.getInputStream();
       int i = len;
       while(((c = input.read())!= -1)&&(i-- > 0))
       {
       System.out.print((char)c);
       }
       input.close();
      }
      else
      {
       System.out.println("no content available");
      }
}}是不是没连接上??和路由器什么的有关吗

解决方案 »

  1.   

    你尝试连接的网址会自动重定向到http://www.mhprofessional.com/templates/112-computing.php所以length会返回-1
    至于为什么-1我也不清楚,我只是知道代码没什么大问题,就是连接网址的问题,如果URL换成http://www.tsinghua.edu.cn以html为主页的没有任何问题
      

  2.   

    getContentLength():返回 content-length 头字段的值,或者如果内容长度未知,则返回 -1
      

  3.   

      System.out.println("content-type:"+ hpcn.getConnectTimeout());
    有问题吧
      

  4.   

    import java.net.URL;
    import java.net.HttpURLConnection;
    import java.util.List;
    import java.util.Map;public class URLDemo {    public static void main(String[] args)throws Exception {
            URL hp = new URL("http://www.osborne.com");
            HttpURLConnection hpcn = (HttpURLConnection)hp.openConnection();
            hpcn.setInstanceFollowRedirects(false);        Map<String,List<String>> headers = hpcn.getHeaderFields();
            for (String h:headers.keySet()) {
                System.out.printf("%s : %s%n",h, headers.get(h));
            }
        }
    }
    null : [HTTP/1.1 302 Found]
    Date : [Mon, 19 Sep 2011 15:15:23 GMT]
    Content-Length : [231]
    Location : [http://www.mhprofessional.com/category/?cat=112]
    Keep-Alive : [timeout=5, max=100]
    Connection : [Keep-Alive]
    Content-Type : [text/html; charset=iso-8859-1]
    Server : [Apache]        hpcn.setInstanceFollowRedirects(true);
    null : [HTTP/1.1 200 OK]
    Date : [Mon, 19 Sep 2011 15:17:23 GMT]
    Transfer-Encoding : [chunked]
    Expires : [Thu, 19 Nov 1981 08:52:00 GMT]
    Keep-Alive : [timeout=5, max=100]
    Set-Cookie : [PHPSESSID=303030e8256194a26d3e695272554883; path=/]
    Connection : [Keep-Alive]
    Content-Type : [text/html]
    Server : [Apache]
    Cache-Control : [no-store, no-cache, must-revalidate, post-check=0, pre-check=0]
    Pragma : [no-cache]
      

  5.   

    是呀,换个网址就没事了,www.baidu.com就可以