简体   繁体   中英

A java.net.ConnectException being thrown when using HttpURLConnection

huc.connect() is throwing the exception. The stack trace below is what gets printed. If I change the url by adding www so the string is " http://www.sas.com/store/books " then it works fine. I did try increasing the connection timeout all the way up to a minute, but the timeout exception was still thrown. Anyone have any ideas why that happens?

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

stack trace:

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)

You should play around with the HttpURLConnection. It's likely that it is redirecting you to www.sas.com. Check the response code and the headers - I think once you do that you'll find your problem

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM