Realizar una busqueda en Google

Libreria necesarias:

  • json-lib-2.4-jdk15
  • ezmorph
  • commons-beanutils-1.7
  • commons-collections
  • commons-logging-1.1.1
  • commons-lang
  • Salida
    =====================================================
    [ Resultados de la Busqueda ]

    Titulo: Python Tutorials – Tutorialized
    URL : http://www.tutorialized.com/tutorials/Python/1
    Titulo: PyCon 2011: Advanced Python 1 Tutorial « The Mouse Vs. The Python
    URL : http://www.blog.pythonlibrary.org/2011/03/09/pycon-2011-advanced-python-1-tutorial/
    Titulo: Tutorial Python 1 – Android Market
    URL : https://market.android.com/details%3Fid%3Dappinventor.ai_nitronat.tutorial_python_1
    Titulo: Python 1: Installation and beginner's tutorial.? – YouTube
    URL : http://www.youtube.com/watch%3Fv%3DNlK_f39eXCE

    =====================================================

    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.io.UnsupportedEncodingException;
    import java.net.MalformedURLException;
    import java.net.URL;
    import java.net.URLConnection;
    import java.net.URLEncoder;
    import java.util.Iterator;
    import java.util.Vector;
    
    import net.sf.json.JSONArray;
    import net.sf.json.JSONObject;
    /**
     * @author Leyer
     */
    public class GoogleSearch{
    	public static String baseUrl       = "http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=";
    	
    	private String securityStuff = null;
    
    	public static final int DEFAULT_PAGE_NUMBER =1;
    	
    	private int page = -1;
    	
    	private Vector<Result> _results =new Vector<GoogleSearch.Result>();
    
    	private String key;
    	public GoogleSearch(String key){
    		this.key =key;
    		this.securityStuff="&key="+key+"&start=";
    	}
    	class Result {
    		private String title = null;
    		private URL    url   = null;
    		
    		public Result(String title,URL url){
    			this.title= title;
    			this.url=url;
    		}
    		public String getTitle() {
    			return title;
    		}
    		public URL getUrl() {
    			return url;
    		}
    	}
    	public Vector<Result> search(String query,int page){
    		try {
    		setPageNumber(page);
    		_results= search(query);
    		} catch (IOException e) {
    			e.printStackTrace();
    		}
    		return _results;
    	}
    	private int getPageNumber() {
    		return page;
    	}
    	private void setPageNumber(int page) {
    		this.page = page;
    	}
    	public Vector<Result> search(String query) throws IOException{
    		  URLConnection connection = null;
    		  
    		try {
    			if(page != -1){
    				this.securityStuff="&key="+key+"&source=uds&filter=0&start="+getPageNumber();
    			}
    			else{
    				this.securityStuff="&key="+key+"&source=uds&filter=0&start="+DEFAULT_PAGE_NUMBER;
    			}
    			connection = new URL( baseUrl + URLEncoder.encode(query,"UTF-8") + securityStuff ).openConnection();
    			} catch (MalformedURLException e) {
    				e.printStackTrace();
    			} catch (UnsupportedEncodingException e) {
    				e.printStackTrace();
    			} catch (IOException e) {
    				e.printStackTrace();
    		  }
    		if(connection != null){
    		  String line = null;
    		  StringBuffer response = new StringBuffer();
    		  BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
    		  while((line = reader.readLine()) != null)response.append(line);
    		  reader.close();
    		  JSONObject obj = (JSONObject)JSONObject.fromObject(response.toString());
    		  if(obj.get("responseData") instanceof JSONObject){
    			  JSONObject responseData = (JSONObject)obj.get("responseData");
    			  if(responseData!=null){
    				  JSONArray results=(JSONArray)responseData.get("results");
    				  Iterator<?> iterator= results.iterator();
    				  while(iterator.hasNext()){
    					JSONObject result=(JSONObject)iterator.next(); 
    					String title=(String) result.get("titleNoFormatting");
    					URL url= new URL(result.get("url").toString());
    					Result r =new Result(title, url);
    					_results.add(r);
    				  			}
    				  	}
    		  		}else{
    				  	System.exit(0);
    			  	}
    		  }
    		  return _results;
    	}
      public static void main(String[] args)  {
    
    	  String key = "***********";
    	  String query ="tutorial python";
    	  GoogleSearch googleSearch=new GoogleSearch(key);
    	  try {
    		Vector<Result> results = googleSearch.search(query);
    		if(results.size()>0){
    		Iterator<Result> iterator = results.iterator();		
    		System.out.println("[    Resultados de la Busqueda  ]");
    		System.out.println();
    		while(iterator.hasNext()){
    			Result result = iterator.next();
    			System.out.println("Titulo: "+result.getTitle());
    			System.out.println("URL   : "+result.getUrl());
    				}
    			}else{
    				System.out.println("No hubieron resultados");
    			
    			}
    	} catch (Exception e) {
    		e.printStackTrace();
    	}
    	  }
      
    
    
    Anuncios

    One Comment to “Realizar una busqueda en Google”

    1. Hi there, i read your blog from time to time and i own a similar one
      and i was just wondering if you get a lot of spam
      feedback? If so how do you stop it, any plugin or anything you can recommend?

      I get so much lately it’s driving me crazy so any support is very much appreciated.

    Responder

    Introduce tus datos o haz clic en un icono para iniciar sesión:

    Logo de WordPress.com

    Estás comentando usando tu cuenta de WordPress.com. Cerrar sesión / Cambiar )

    Imagen de Twitter

    Estás comentando usando tu cuenta de Twitter. Cerrar sesión / Cambiar )

    Foto de Facebook

    Estás comentando usando tu cuenta de Facebook. Cerrar sesión / Cambiar )

    Google+ photo

    Estás comentando usando tu cuenta de Google+. Cerrar sesión / Cambiar )

    Conectando a %s

    A %d blogueros les gusta esto: