jetdw
jetdw
2013-07-23 09:48

java读取网页数据超时

已采纳

[code="java"]public static void main(String[] args) throws IOException {
getWebData("http://bbs.csdn.net/topics/380263902");
}

private static String getWebData(String strurl) { 
    try { 
        URL url = new URL(strurl); 
        // 打开连接,此处只是创建一个实例,并没有真正的连接 
        HttpURLConnection httpCon = (HttpURLConnection) url.openConnection(); 
        httpCon.setConnectTimeout(300000); 
        httpCon.setReadTimeout(300000); 


        httpCon.connect();//建立连接 
        InputStream inputStream = httpCon.getInputStream(); 
        InputStreamReader inputReader = new InputStreamReader(inputStream,"utf-8"); 
        BufferedReader bufferReader = new BufferedReader(inputReader); 
        StringBuffer sb = new StringBuffer(); 
        String inputLine = null;   
        while ((inputLine = bufferReader.readLine()) != null) {    
            sb.append(inputLine+"\n"); 
        }    
        bufferReader.close();   
        inputReader.close(); 
        inputStream.close(); 
        httpCon.disconnect(); 
        System.out.println(sb.toString().trim()); 
        return sb.toString(); 
    } catch (Exception e) { 
        // TODO Auto-generated catch block 
        e.printStackTrace(); 
    } 
    System.out.println("======================================================="); 
    return null; 
}[/code]

代码如上,但是执行上面代码报如下错误

java.net.ConnectException: Connection timed out: connect
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(Unknown Source)
at java.net.PlainSocketImpl.connectToAddress(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at sun.net.NetworkClient.doConnect(Unknown Source)
at sun.net.www.http.HttpClient.openServer(Unknown Source)
at sun.net.www.http.HttpClient.openServer(Unknown Source)
at sun.net.www.http.HttpClient.(Unknown Source)
at sun.net.www.http.HttpClient.New(Unknown Source)
at sun.net.www.http.HttpClient.New(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getNewHttpClient(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.plainConnect(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.connect(Unknown Source)
at test.getWebData(test.java:30)
at test.main(test.java:18)

我通过IE浏览器是可以打开http://bbs.csdn.net/topics/380263902该页面的,但是通过代码就不能获取页面数据,不知道是什么原因

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

3条回答

  • cqskyeagle cqskyeagle 8年前

    应该查看一下 你的杀毒软件或者防火墙之类的东西,我以前也遇见过 webservice死活也联不通。后来关闭了杀毒软件和防火墙就o了!

    点赞 评论 复制链接分享
  • hot002 hot002 8年前

    1 看下是不是需要设置代理

    2 打开FIREFOX把请求头记下来,在httpCon里相应参数都设置成一样

    点赞 评论 复制链接分享
  • lzzjn lzzjn 8年前

    http 一般需要设置请求方法把 有些网站 限定了方法 加上 get post 试试

    点赞 评论 复制链接分享

相关推荐