0

我对java很陌生,实际上我刚刚开始学习它我尝试做一个练习,练习是阅读网页的前五行开始我写了这段代码:

import java.io.* ;

import java.net.URL ;

class testcode {

    public static void main(String[] args) throws Exception {
        URL address = new URL("http://www.yahoo.com/") ;
        InputStream is = address.openStream() ;
        InputStreamReader isr = new InputStreamReader(is) ;
        BufferedReader reader = new BufferedReader(isr) ;
        String line = reader.readLine() ;
    }

}

但是当我通过 Eclipse 运行这段代码时,我得到了这个:

Exception in thread "main" java.net.ConnectException: Connection refused: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source)
at java.net.AbstractPlainSocketImpl.connect(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.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.<init>(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 sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
at java.net.URL.openStream(Unknown Source)
at test.testcode.main(testcode.java:10)

为什么会这样!?

当然,当我不将 throws Exception 部分放在开头时,我会得到格式错误的 url 异常!

PS:我的网络连接正常!

有人可以帮助我并解释为什么这样做时会发生这种情况吗?我有很好的 C++ 背景,所以请尽可能深入地解释:D

4

1 回答 1

2

您的程序似乎无法连接到该 URL。你在代理后面使用互联网吗?如果是这样,请确保您的程序已相应配置。一种方法是使用此代码:

System.setProperty("http.proxyHost", "proxy.mydomain.com");
System.setPropery("http.proxyPort", "8080");
于 2013-07-27T20:13:14.910 回答