Categorías
Google API

Llamar a la API de búsqueda de Google en Java

Esta publicación muestra cómo llamar a la API de búsqueda de Google en un programa estándar de Java.

1. Un enfoque ingenuo

El método a continuación no requiere ninguna biblioteca de terceros, pero el formato del resultado no es legible y no podemos encontrar lo que necesitamos a través del texto del resultado.

public static void main(String[] args) throws IOException {
 
	String address = "http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=";
	String query = "java tutorial";
	String charset = "UTF-8";
 
	URL url = new URL(address + URLEncoder.encode(query, charset));
 
	BufferedReader in = new BufferedReader(new InputStreamReader(
			url.openStream()));
	String str;
 
	while ((str = in.readLine()) != null) {
		System.out.println(str);
	}
 
	in.close();
}

2. Un mejor enfoque

Afortunadamente, alguien ya escribió una biblioteca para que convirtiéramos el formato Json a la clase Java. La biblioteca se llama «Google Gson», se puede descargar aquí: http://code.google.com/p/google-gson/downloads/list. Necesitamos usar gson-2.2.1.jar dentro del archivo zip.

El siguiente código ahora puede devolvernos las URL.

package google.api.search;
 
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URL;
import java.net.URLEncoder;
import java.util.List;
import com.google.gson.Gson;
 
public class TestGoogleSea {
 
	public static void main(String[] args) throws IOException {
 
		String address = "http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=";
		String query = "programcreek";
		String charset = "UTF-8";
 
		URL url = new URL(address + URLEncoder.encode(query, charset));
		Reader reader = new InputStreamReader(url.openStream(), charset);
		GoogleResults results = new Gson().fromJson(reader, GoogleResults.class);
 
		int total = results.getResponseData().getResults().size();
		System.out.println("total: "+total);
 
		// Show title and URL of each results
		for(int i=0; i<=total-1; i++){
			System.out.println("Title: " + results.getResponseData().getResults().get(i).getTitle());
			System.out.println("URL: " + results.getResponseData().getResults().get(i).getUrl() + "n");
 
		}
	}
}
 
 
class GoogleResults{
 
    private ResponseData responseData;
    public ResponseData getResponseData() { return responseData; }
    public void setResponseData(ResponseData responseData) { this.responseData = responseData; }
    public String toString() { return "ResponseData[" + responseData + "]"; }
 
    static class ResponseData {
        private List<Result> results;
        public List<Result> getResults() { return results; }
        public void setResults(List<Result> results) { this.results = results; }
        public String toString() { return "Results[" + results + "]"; }
    }
 
    static class Result {
        private String url;
        private String title;
        public String getUrl() { return url; }
        public String getTitle() { return title; }
        public void setUrl(String url) { this.url = url; }
        public void setTitle(String title) { this.title = title; }
        public String toString() { return "Result[url:" + url +",title:" + title + "]"; }
    }
}

Producción:

total: 4

Título: ProgramCreek.com
URL: http://www.programcreek.com/

Título: Los 8 mejores diagramas para comprender Java – ProgramCreek.com
URL: http://www.programcreek.com/2013/09/top-8-diagrams-for-understanding-java/

Título: Los 10 métodos principales para matrices Java – ProgramCreek.com
URL: http://www.programcreek.com/2013/09/top-10-methods-for-java-arrays/

Título: Tutoriales de Eclipse JDT – ProgramCreek.com
URL: http://www.programcreek.com/2011/01/best-java-development-tooling-jdt-and-astparser-tutorials/

Ahora tiene una lista de resultados de búsqueda de Google legibles mediante el uso de la API de búsqueda y Gson, pero puede notar rápidamente que el resultado solo contiene 4 resultados, pero necesitamos más.

Esto no es un error, está diseñado para ser así. Lo que puede hacer es agregar un parámetro a la url «start = #» como el SIGUIENTE:

String address = "http://ajax.googleapis.com/ajax/services/search/web?v=1.0&start=4&q=";

Si el inicio se establece en 4, tenemos los resultados del 5º al 8º; si el número es 100, tenemos los resultados del 101 al 104, y así sucesivamente. Los siguientes son resultados cuando el inicio es 4.

Título: Junior Ranger Programa – Creek Critters | Amigos de Tryon Creek
URL: http://www.tryonfriends.org/junior-ranger-program-creek-critters/

Título: 10 03 13 SCHS vs Sanford, Full programa, Creek gana! – YouTube
URL: http://www.youtube.com/watch%3Fv%3Dv0GEi-7LgYg

Título: Programcreek.com: Referencias inversas en expresiones regulares de Java
URL: http://www.java.net/story/programcreekcom-backreferences-java-regular-expressions

Título: California, condado de Marin, McIsaac Ranch, STRAW programa arroyo
URL: http://www.davidsanger.com/stockimages/2-216-47.STRAW

3. Ponlo en un bucle para obtener más resultados.

Puede poner esto en un bucle y cambiar el número de inicio en cada bucle para obtener más resultados.

for (int i = 0; i < 20; i = i + 4) {
	String address = "http://ajax.googleapis.com/ajax/services/search/web?v=1.0&start="+i+"&q=";
 
	String query = "Programcreek";
	String charset = "UTF-8";
 
	URL url = new URL(address + URLEncoder.encode(query, charset));
	Reader reader = new InputStreamReader(url.openStream(), charset);
	GoogleResults results = new Gson().fromJson(reader, GoogleResults.class);
 
	// Show title and URL of each results
	for (int m = 0; m <= 3; m++) {
		System.out.println("Title: " + results.getResponseData().getResults().get(m).getTitle());
		System.out.println("URL: " + results.getResponseData().getResults().get(m).getUrl() + "n");
	}
}

Debe tener en cuenta que Google no permite demasiadas solicitudes en un período de tiempo determinado.