Read a GIF or CLASS from an URL save it locallyTag(s): Networking


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

 public class SuckURL {
   String aFile;
   String aURL;

   public static void main(String args[]) {
     // GIF  JAVA How-to  at Real's Home
     String url = 
       "http://www.rgagnon.com/images/";
     SuckURL b = new SuckURL(url, "jht.gif");
     b.doit();
   }

   SuckURL(String u, String s){ 
     aURL  = u;
     aFile = s;
   }

   public void doit() {
     DataInputStream di = null;
     FileOutputStream fo = null;
     byte [] b = new byte[1];  
       
     try {
       System.out.println("Sucking " + aFile);
       System.out.println("   at " + aURL );
       // input 
       URL url = new URL(aURL + aFile);
       URLConnection urlConnection = url.openConnection();
       urlConnection.connect();
       di = new DataInputStream(urlConnection.getInputStream());

       // output
       fo = new FileOutputStream(aFile);

       //  copy the actual file
       //   (it would better to use a buffer bigger than this)
       while(-1 != di.read(b,0,1)) 
         fo.write(b,0,1);
         di.close();  
         fo.close();                
     }
     catch (Exception ex) { 
       System.out.println("Oups!!!");
       ex.printStackTrace(); 
       System.exit(1);
     }
     System.out.println("done.");  
   }
}

This example dumps a page using the HTTPS protocol :

import java.io.*;
import java.net.*;
public class URLReader {
  public static void main(String[] args) throws Exception {
    // no longer necessary since JSSE is now included in
    // recent jdk release...
    // Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
    // System.setProperty("java.protocol.handler.pkgs",
    //     "com.sun.net.ssl.internal.www.protocol");  
  
    URL url = new URL("https://www.thawte.com");
    HttpURLConnection con = (HttpURLConnection) url.openConnection();

    BufferedReader in = new BufferedReader(
                new InputStreamReader(
                con.getInputStream()));
    String inputLine;

    while ((inputLine = in.readLine()) != null)
        System.out.println(inputLine);
    in.close();
    }
}

There is an issue with root certificate from Verisign (jdk142 or less, you have exception talking about "untrusted server"), you may want to review this note : http://sunsolve.sun.com/search/document.do?assetkey=1-26-57436-1.


blog comments powered by Disqus