home *** CD-ROM | disk | FTP | other *** search
/ The Net: Ultimate Internet Guide / WWLCD1.ISO / pc / java / pr8adpl7 / webdevice.java < prev    next >
Encoding:
Java Source  |  1996-08-14  |  1.6 KB  |  71 lines

  1. // WebDevice
  2. // A device driver for reading from a URL.
  3. import java.net.*;
  4. import java.io.*;
  5. import java.util.Date;
  6.  
  7. public class WebDevice extends DeviceDriver
  8. {
  9.     // read
  10.     // Valid parameters are:
  11.     //  URL: <url>
  12.     // The returned message contains all the headers from the HTTP request.
  13.     Message read(Message msg, ServerClient s) throws IOException
  14.     {
  15.     String urlstr = msg.find("URL");
  16.     if (urlstr == null)
  17.         throw new IOException("No URL given");
  18.  
  19.     // connect to the url
  20.     URL u = null;
  21.     URLConnection url = null;
  22.     try {
  23.         u = new URL(urlstr);
  24.         url = u.openConnection();
  25.         }
  26.     catch(MalformedURLException e)
  27.         throw new IOException("Bogus URL");
  28.     LineInputStream in;
  29.     try {
  30.         url.connect();
  31.         in = new LineInputStream(url.getInputStream());
  32.         }
  33.     catch(IOException e)
  34.         throw new IOException("URL connect failed : "+e.getMessage());
  35.  
  36.     // Read data
  37.     Message r = new Message();
  38.     r.add("Reply","Data");
  39.     int len = url.getContentLength();
  40.     try {
  41.         if (len != -1) {
  42.             byte arr[] = new byte[len];
  43.             in.readdata(arr);
  44.             r.setdata(arr);
  45.             }
  46.         else {
  47.             BufferOutputStream buf = new BufferOutputStream();
  48.             int c;
  49.             while(true) {
  50.                 if ((c = in.read()) < 0) break;
  51.                 buf.write(c);
  52.                 }
  53.             r.setdata(buf.getarray());
  54.             }
  55.         }
  56.     catch(IOException e)
  57.         throw new IOException("Error reading data from URL");
  58.  
  59.     // get useful headers
  60.     String ct = url.getContentType();
  61.     if (ct == null) ct = "application/octec-stream";
  62.     r.add("Content-type",ct);
  63.     String ce = url.getContentEncoding();
  64.     if (ce != null) r.add("Content-encoding",ce);
  65.     long lm = url.getLastModified();
  66.     if (lm != 0) r.add("Last-modified",new Date(lm).toString());
  67.     return r;
  68.     }
  69. }
  70.  
  71.