home *** CD-ROM | disk | FTP | other *** search
Java Source | 1996-08-14 | 1.6 KB | 71 lines |
- // WebDevice
- // A device driver for reading from a URL.
- import java.net.*;
- import java.io.*;
- import java.util.Date;
-
- public class WebDevice extends DeviceDriver
- {
- // read
- // Valid parameters are:
- // URL: <url>
- // The returned message contains all the headers from the HTTP request.
- Message read(Message msg, ServerClient s) throws IOException
- {
- String urlstr = msg.find("URL");
- if (urlstr == null)
- throw new IOException("No URL given");
-
- // connect to the url
- URL u = null;
- URLConnection url = null;
- try {
- u = new URL(urlstr);
- url = u.openConnection();
- }
- catch(MalformedURLException e)
- throw new IOException("Bogus URL");
- LineInputStream in;
- try {
- url.connect();
- in = new LineInputStream(url.getInputStream());
- }
- catch(IOException e)
- throw new IOException("URL connect failed : "+e.getMessage());
-
- // Read data
- Message r = new Message();
- r.add("Reply","Data");
- int len = url.getContentLength();
- try {
- if (len != -1) {
- byte arr[] = new byte[len];
- in.readdata(arr);
- r.setdata(arr);
- }
- else {
- BufferOutputStream buf = new BufferOutputStream();
- int c;
- while(true) {
- if ((c = in.read()) < 0) break;
- buf.write(c);
- }
- r.setdata(buf.getarray());
- }
- }
- catch(IOException e)
- throw new IOException("Error reading data from URL");
-
- // get useful headers
- String ct = url.getContentType();
- if (ct == null) ct = "application/octec-stream";
- r.add("Content-type",ct);
- String ce = url.getContentEncoding();
- if (ce != null) r.add("Content-encoding",ce);
- long lm = url.getLastModified();
- if (lm != 0) r.add("Last-modified",new Date(lm).toString());
- return r;
- }
- }
-
-