1

我想要使​​用以下 java 代码的 http get 请求的请求。但是,我不确定我得到了以下异常。

    import java.net.*;
import java.io.*;

public class API {
    public static void main(String[] args) throws Exception {
        URL oracle = new URL("http://www.oracle.com/");
        URLConnection yc = oracle.openConnection();
        BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream()));
        String inputLine;
        while ((inputLine = in.readLine()) != null) 
            System.out.println(inputLine);
        in.close();
    }
}

错误或异常如下:

Exception in thread "main" java.net.ConnectException: Connection timed out: connect
    at java.net.DualStackPlainSocketImpl.connect0(Native Method)
    at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:69)
    at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:337)
    at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:198)
    at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:180)
    at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:157)
    at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:391)
    at java.net.Socket.connect(Socket.java:579)
    at java.net.Socket.connect(Socket.java:528)
    at sun.net.NetworkClient.doConnect(NetworkClient.java:180)
    at sun.net.www.http.HttpClient.openServer(HttpClient.java:388)
    at sun.net.www.http.HttpClient.openServer(HttpClient.java:483)
    at sun.net.www.http.HttpClient.<init>(HttpClient.java:213)
    at sun.net.www.http.HttpClient.New(HttpClient.java:300)
    at sun.net.www.http.HttpClient.New(HttpClient.java:316)
    at sun.net.www.protocol.http.HttpURLConnection.getNewHttpClient(HttpURLConnection.java:992)
    at sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:928)
    at sun.net.www.protocol.http.HttpURLConnection.connect(HttpURLConnection.java:846)
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1296)
    at API.main(API.java:8)
4

2 回答 2

4

我猜你有防火墙,它阻止了这个 HTTP 获取请求。

您的代码应该按预期工作。Java 运行时之外的东西正在阻止连接。

于 2013-09-23T10:12:05.030 回答
1

Check whether you can ping to http://www.oracle.com/.

If you can ping check whether you are behind a proxy server.

If so provide -Dhttp.proxyHost and -Dhttp.proxyPort while starting the JVM

java -Dhttp.proxyHost=<Your Proxy Server Name/IP> -Dhttp.proxyPort=<Your Proxy Server Port>
于 2013-09-23T10:23:32.047 回答