javaurlconnectiondownloadconnectexception

Java class to downlaod file


I am trying to download a file using simple java class using the following code:

Simple java class to download the file

Its giving me following error for my url:

java.net.ConnectException: Connection refused: connect  
at java.net.PlainSocketImpl.socketConnect(Native Method)  
at java.net.PlainSocketImpl.doConnect(Unknown Source)  
at java.net.PlainSocketImpl.connectToAddress(Unknown Source)  
at java.net.PlainSocketImpl.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.getOutputStream(Unknown Source)  
at Download.URLSetUp(Download.java:32)  
at Download.main(Download.java:16)  

Please let me know if any of you have got any soultion.

Thanks
Sneha


Solution

  • Since Java 1.5 you can also pass a java.net.Proxy instance to the openConnection() method:

    //Proxy instance, proxy ip = 192.168.0.1 with port 8080  
    
    Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("192.168.0.1", 8080));
    URL url = new URL("http://www.sheldonbrown.com/web_sample1.html");
    HttpURLConnection uc = (HttpURLConnection)url.openConnection(proxy);
    uc.connect ();
    
    OutputStreamWriter wr = new OutputStreamWriter(uc
                  .getOutputStream());  
    
    BufferedReader rd = new BufferedReader(new InputStreamReader(uc
                    .getInputStream()));