我对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)
为什么会这样?!
当然,当我在开始时抛出异常部分时,我得到了格式错误的网址异常!
PS:我的网络连接工作正常!
有人可以帮助我并解释为什么这样做会发生这种情况? 我有一个非常好的c ++背景,所以请尽可能深入解释:D
答案 0 :(得分:2)
您的程序似乎无法连接到该网址。您是否使用互联网代理?如果是这样,那么请确保相应地配置了您的程序。一种方法是使用此代码:
System.setProperty("http.proxyHost", "proxy.mydomain.com");
System.setPropery("http.proxyPort", "8080");