
Todo el mundo usa Google. Yo hace tiempo que deje de usar Yahoo, Altavista, HotBoot, etc. Google conquistó el ciberspacio. Pero lo genial es que usted puede utilizar ese poder en sus aplicaciones (no comerciales, claro está) usando el API web de Google.
Para usarla, sólo bajesela, sólo necesita abrir una cuenta en Google para obtener una clave de accceso y después es sólo echar código (claro, después de leer la referencía).
La mejor forma de hacer esto es primero probar la búsqueda en Google (usando la forma web) y después corriendo la aplicación.
!Suficiente habladera de paja!. Le voy a mostrar un ejemplo prático de como utilizar el API con Java (Google provee soporte para varios lenguajes, como Perl).
Si usted es como yo, seguramente no sabe que la directora de la pelicula “Macu, La Mujer del policia” es Solveig Hoogesteijn, y por ello usted ha decidido hacer un pequeño programa para buscar información en Internet usando Google. Lo primero que hace es definir el programa de búsqueda:
1:package com.blogspot.elangelnegro;
2:
3:import com.google.soap.search.GoogleSearch;
4:import com.google.soap.search.GoogleSearchResult;
5:import com.google.soap.search.GoogleSearchResultElement;
6:import com.google.soap.search.GoogleSearchFault;
7:
8:import java.util.ResourceBundle;
9:
10:/**
11: * This class shows how to use the Google API to perform searchs using Java.
12: * In order to make the script work, you will need a key
13: * that can be obtained from <a href="http://www.google.com/apis/download.html">here</a>
14: * @author Jose Vicente Nunez Zuleta (josevnz@yahoo.com)
15: * @version 0.1 - 11/22/2004
16: * @see http://www.google.com/apis/reference.html
17: */
18:public final class GoogleQuickSearch {
19:
20: private static final ResourceBundle BUNDLE = ResourceBundle.getBundle(GoogleQuickSearch.class.getName());
21: private GoogleQuickSearch() {}
22:
23: /**
24: * Command line arguments processing.
25: * @param args Only the first argument is considered for the search, the rest is discarded
26: * @throws GoogleSearchFault if there is any problem performing the search
27: * @since 0.1
28: */
29: public static void main(String [] args) throws GoogleSearchFault {
30: if (! ((args != null) && (args.length == 1)) ) {
31: throw new NullPointerException("Please provide a search query");
32: }
33: GoogleSearch search = new GoogleSearch();
34: search.setKey(BUNDLE.getString("com.blogspot.elangelnegro.GoogleQuickSearch.query.mandatory.key"));
35: search.setQueryString(args[0]);
36: search.setSafeSearch(false); // Do not filter my results, thanks
37: search.setLanguageRestricts(BUNDLE.getString("com.blogspot.elangelnegro.GoogleQuickSearch.query.optional.languajes"));
38: GoogleSearchResult result = search.doSearch();
39:
40: // The section 2.7, "Limitations" limitations on the search functionality
41: int totalResults = result.getEstimatedTotalResultsCount();
42: GoogleSearchResultElement[] detail = result.getResultElements();
43: for (int i=0; i < detail.length; i++) {
44: // Eliminate all the HTML formatting from the title. This is not complete by any means
45: System.out.println(detail[i].getTitle().replaceAll("<b>", "").replaceAll("</b>", "").replaceAll(""", "\"") + ": ");
46: System.out.println("\t" + detail[i].getURL());
47: detail[i]=null;
48: }
49: }
50:}
El procedimiento es muy sencillo, primero construya una búsqueda con la clase ‘com.google.soap.search.GoogleSearch’, obtenga un conjunto de resultados con ‘com.google.soap.search.GoogleSearchResult’ y luego itere sobre cada uno de ellos con ‘com.google.soap.search.GoogleSearchResultElement’.
Si usted se dió cuenta, el programa de búsqueda carga un archivo de recursos (ResourceBundle) en el cual tenemos nuestra llave y otros parametros que no van a cambiar frecuentemente durante la ejecución del programa:
1:# Required key to use the Google API
2:com.blogspot.elangelnegro.GoogleQuickSearch.query.mandatory.key=XXXXXXXXXXXXXAA
3:# Languajes to search for (restrict the results)
4:com.blogspot.elangelnegro.GoogleQuickSearch.query.optional.languajes=lang_es|lang_en|lang_sv|lang_fr
Y si es tan perezoso como yo, entonces seguramente utilizará ant para compilar está pequeña aplicación:
1:<project default="build" name="GoogleQuickSearch" basedir=".">
2: <!-- System wide properties -->
3: <property name="version" value="0.0" />
4: <property name="src" value="src" />
5: <property name="build" value="build" />
6: <property name="dist" value="dist" />
7: <property name="test" value="test" />
8: <property name="etc" value="etc" />
9: <property name="scripts" value="scripts" />
10: <property name="lib" value="lib" />
11: <property name="doc" value="doc" />
12: <property name="jar.google" value="${user.dir}/googleapi/googleapi.jar" />
13: <property name="jarfile" value="${dist}/${ant.project.name}-${version}.jar" />
14: <property name="tarfile" value="${ant.project.name}-${version}.tar.gz" />
15: <property name="classpath" value="${jar.google}:${build}:." />
16: <target name="init" description="Prepare required directories before all the other targets">
17: <mkdir dir="${build}"/>
18: <mkdir dir="${dist}"/>
19: <mkdir dir="${doc}/javadoc"/>
20: </target>
21: <target name="clean" description="Perform directory cleanup">
22: <delete includeEmptyDirs="yes" failonerror="no">
23: <fileset dir="${build}" />
24: <fileset dir="${dist}" />
25: <fileset dir="${doc}/javadoc" />
26: </delete>
27: </target>
28: <target name="build" depends="init" description="Build the program source code">
29: <javac srcdir="${src}" destdir="${build}" includes="**/*.java" classpath="${classpath}"/>
30: <copy description="Copy the ResourceBundles for all the classes" todir="${build}" overwrite="true">
31: <fileset dir="${src}">
32: <include name="**/*.properties"/>
33: </fileset>
34: </copy>
35: </target>
36: <target name="doc" depends="init">
37: <javadoc
38: sourcepath="${src}"
39: destdir="${dist}/doc/javadoc"
40: packageList="${basedir}/PackageList.txt"
41: package="true"
42: version="true"
43: use="true"
44: author="true"
45: Header="${ant.project.name} 2004"
46: windowtitle="${ant.project.name} classpath="${classpath}">
47: <bottom><![CDATA[<a href="http://elangelnegro.blogspot.com">
48: <i>Copyright © 2004 Jose Vicente Nunez Zuleta. </i></a>]]></bottom>
49: </javadoc>
50: </target>
51: <target name="jar" depends="build" description="Pack the project sources for distribution">
52: <jar jarfile="${jarfile}" basedir="${build}" description="exclude all the web classes" >
53: <exclude name="**/test/*"/>
54: </jar>
55: </target>
56:</project>
Haciendo un archivo Jar del el programa (el cual contiene nuestro código en Java y el archivo de recursos) lo ejecutamos así:
[josevnz@localhost GoogleQuickSearch]$ java com.blogspot.elangelnegro.GoogleQuickSearch
"Solveig Hoogesteijn"
Solveig Hoogesteijn:
http://www.imdb.com/Name?Hoogesteijn,+Solveig
Keywords for Solveig Hoogesteijn:
http://www.imdb.com/name/nm0393566/filmokey
--FESTIVAL INTERNACIONAL DEL NUEVO CINE LATINOAMERICANO--:
http://www.habanafilmfestival.com/primerplano/index_amplia.php3?ord=4420
Cannes Film Festival:
http://www.festival-cannes.com/perso/index.php?langue=6002&personne=5690
Festival de Cannes:
http://www.festival-cannes.fr/perso/index.php?langue=6001&personne=5690
Victor Cuica - Discografía - Temas de Películas:
http://www.victorcuica.com/disco_sound.htm
Victor Cuica - Biografía:
http://www.victorcuica.com/bio_esp.htm
SOLVEIG HOOGESTEIJN:
http://www.ultimasnoticias.com.ve/ediciones/2003/01/12/p33n1.htm
SOLVEIG HOOGESTEIJN:
http://www.ultimasnoticias.com.ve/ediciones/2003/01/12/p32n1.htm
Actualidad - "La Virgen de los sicarios" proyección en el CELARG ...:
http://www.analitica.com/va/arte/actualidad/7960571.asp
[josevnz@localhost GoogleQuickSearch]$
En un próximo articulo voy a mostrarle como pasarse el limite de 10 resultados máximo de Google y como mejorar las búsquedas.
Sin categoría
Comentarios recientes