NOTE:
These slides have not been updated since 2003. They have been superseded by the book
Anders Møller and Michael Schwartzbach, February 2006 |
INTERACTIVE WEB SERVICES WITH JAVA |
The most relevant classes and methods:
import java.net.*; import java.io.*; public class AltaVista { public static void main (String args[]) { try { // make connection URL url = new URL("http://www.altavista.com/cgi-bin/query?q=" + URLEncoder.encode(args[0])); URLConnection connection = url.openConnection(); connection.setDoInput(true); InputStream in = connection.getInputStream(); // read reply StringBuffer b = new StringBuffer(); BufferedReader r = new BufferedReader(new InputStreamReader(in)); String line; while ((line = r.readLine()) != null) b.append(line); String s = b.toString(); // look for first search result, if any if (s.indexOf(">We found 0 results") != -1) System.out.println("No results found."); else { int i = s.indexOf("\"status='")+9; int j = s.indexOf("'", i); System.out.println("First result: " + s.substring(i, j)); } } catch (Exception e) { e.printStackTrace(); } } } |
(sends a query to the AltaVista search engine and extracts the first result)
Other useful classes in java.net:
COPYRIGHT © 2002-2003 ANDERS MØLLER & MICHAEL I. SCHWARTZBACH |