// URLHandler

import java.net.*;
import java.io.*;
import java.applet.Applet;

public class URLHandler {

/**
 * URLHandler class provides static methods: 
 * fetchURL(), urlExists(), postURL(), appletPrint()
 * Usage: 
 *  if(URLHandler.urlExists(urlString) )
 *     String string = URLHandler.fetchURL(applet, urlString);
 * Example of the call from an applet:
 *  String string = URLHandler.fetchURL(this, "/mydirectory/final.html");
 * Example of the call from an application:
 *  String string = URLHandler.fetchURL(null,"file:///c:/jschool/final.html");
 * @@author Jeff Zhuk
 */


/**
 * @param iApplet ( if null, it behaves as an application)
 * @param iURL (with arguments if needed )
 * @return htmlPage
 */    
/**
 * @param iApplet ( if null, it behaves as an application)
 * @param iURL (with arguments if needed )
 * @return htmlPage
 */    
    public static String fetchURL(Applet iApplet, String iURL) {
        URL url = null;
        try {
            if(iApplet == null)        
                url = new URL("file:///" + 
                  System.getProperty("user.dir") + "/" + iURL);
            else
                url = new URL(iApplet.getCodeBase(), iURL);
            URLConnection urlConn = url.openConnection();
         
           
	         int length=urlConn.getContentLength();
	         ByteArrayOutputStream tempBuffer;
	         if(length<0){
	             tempBuffer=new ByteArrayOutputStream();
	         } else {
	             tempBuffer=new ByteArrayOutputStream(length);
	         }
	         InputStream inStream=urlConn.getInputStream();

             byte buf[] = new byte[1024];
             int cnt = 0;
             while ((cnt = inStream.read(buf)) > 0)  { 
                 tempBuffer.write(buf, 0, cnt);
             }

             byte[] applCode;
	          applCode=tempBuffer.toByteArray();
	          return (new String(applCode) );  // bytes->to string
        } catch(Exception e) {
             System.out.println("InOut.fetchURL:url=" + url + " e=" + e);
             return null;
        }
    }

/**
 * urlExists() uses JDK 1.1 API
 * It checks for URL existence
 * @param iURL to check
 * return true if exists
 */    
    static boolean urlExists(String iURL) {
        try
        {
            HttpURLConnection.setFollowRedirects(true);
            HttpURLConnection con =
              (HttpURLConnection) new URL(iURL).openConnection();
            con.setRequestMethod("HEAD");
            if (con.getResponseCode() == HttpURLConnection.HTTP_OK)
                 return true;
        } catch (Exception e) {
            System.out.println(
              "URLHandler.urlExists:failure to find url=" + iURL + " e=" + e);
       }
       return false;
    }
/**
 * postURL() is to write a string over URL connection
 * @param iURL part of url after the host name
 * @param iInfo to write    
 * @return response from server or null if failure
 */
    public static String postURL(Applet iApplet, String iURL, String iInfo)
    {
if(debug)
System.out.println("InOut.postURL:iURL=" + iURL);    
     URL url = null;
     try {   // example of URL: "http://server.com/postURLdata.pl"
       url = new URL(iApplet.getCodeBase(), iURL); 
if(debug)
System.out.println("InOut.postURL:url=" + url);                    
       URLConnection urlConn=url.openConnection();        
       urlConn.setDoOutput(true); 
       urlConn.setDoInput(true); 
       urlConn.setUseCaches(false); 

       urlConn.setRequestProperty("Content-type", "application/octet-stream"); 
       urlConn.setRequestProperty("Content-length", " "+ iInfo.length()); 

/* It's possible that for specific info another header request is needed
       urlConn.setRequestProperty("Content-Type", 
         "application/x-www-form-urlencoded");

       urlConn.setRequestProperty( "Authorization",
         "Basic " + base64Encode ("buford:OldParanoid") );
*****************************************************************/
       
       DataOutputStream outData=new DataOutputStream(urlConn.getOutputStream());
       
       outData.writeBytes(iInfo);  // example of info: fname=news.htm&info=....
       outData.flush();
       outData.close();

       // get response from the server  
       DataInputStream inData=new DataInputStream(urlConn.getInputStream());

if(debug)
System.out.println("DataInPutStream:" + inData);         
       String response = ""; 
       String line = "";
       while ((line=inData.readLine()) != null){
       response = response + line;
if(debug)       
System.out.println(line);
       }
       inData.close();
      
     } catch(Exception e){
       System.out.println("InOut.postURL:url=" + url + " e="+e);  
       return null;            
     } 
     return response;
    }    
/**
 * appletPrint() method uses postURL() to write file to server
 * and then shows this file in the browser window
 * @param iApplet
 * @param iURL url to server support program ("http://server.com/support.pl"
 * @param iInfo (includes necessary arguments to support.pl)
 * @return success 
 */
    public static boolean appletPrint(Applet iApplet, String iURL, String iInfo) {
        // post data to the server and get back file name like "news.htm"
        String fname = postURL(iApplet, iURL, iInfo);
        
        if(fname == null)
            return false;
        try {            
            iApplet.getAppletContext().showDocument(
              new URL(iApplet.getCodeBase(), fname) );
        } catch(Exception e) {
            iApplet.showStatus("appletPrint.failure: " + e);  
            return false;
        }            
        return true;          
    }         
}

Back To Java Networking