使用HttpURLConnection时抛出的java.net.ConnectException

时间:2016-07-13 19:53:27

标签: java http url httpurlconnection

huc.connect()抛出异常。下面的堆栈跟踪是打印的内容。如果我通过添加www更改网址,则字符串为" http://www.sas.com/store/books"然后它工作正常。我确实尝试将连接超时一直增加到一分钟,但仍然抛出超时异常。任何人都有任何想法为什么会这样?

    try
    {
        URL u = new URL("http://sas.com/store/books");
        HttpURLConnection huc =  (HttpURLConnection)u.openConnection();
        huc.connect(); 
    }
    catch(IOException e)
    {
        e.printStackTrace();
    }

堆栈跟踪:

java.net.ConnectException: Connection timed out: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:79)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:339)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:200)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:182)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
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:432)
at sun.net.www.http.HttpClient.openServer(HttpClient.java:527)
at sun.net.www.http.HttpClient.<init>(HttpClient.java:211)
at sun.net.www.http.HttpClient.New(HttpClient.java:308)
at sun.net.www.http.HttpClient.New(HttpClient.java:326)
at sun.net.www.protocol.http.HttpURLConnection.getNewHttpClient(HttpURLConnection.java:996)
at sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:932)
at sun.net.www.protocol.http.HttpURLConnection.connect(HttpURLConnection.java:850)
at support.Test.main(Test.java:22)

2 个答案:

答案 0 :(得分:0)

你应该玩HttpURLConnection。它可能会将您重定向到www.sas.com。检查响应代码和标题 - 我认为一旦你这样做,你就会发现你的问题

答案 1 :(得分:0)

检查导入,应为import java.net.HttpURLConnection