Search Google Programmatically with Java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
 
public class Google_Search {
    private final String _url;
    private URL _url_obj;
    private HttpURLConnection _connection;
    private final String _userAgent;
    private int _responseCode;
    private StringBuffer _totalResults;
    private final int _quantity;
    private final int _start;
    private final String _searchTerm;
 
    public Google_Search(String SearchTerm){
        _url = "http://www.google.com";
        _userAgent = "(Mozilla/5.0 (Windows; U; Windows NT 6.0;en-US; rv:1.9.2)" + 
                " Gecko/20100115 Firefox/3.6)";
        _quantity = 100;
        _start = 0;
        _searchTerm = SearchTerm;
    }
 
 
    public int ResponseCode(){
        return _responseCode;
    }
 
    public StringBuffer GetResults(){
        return _totalResults;
    }
 
    public void Search(){
        try {
            _url_obj = new URL(_url + "/search?num="+_quantity+"&start=" + 
                    _start + "&hl=en&meta=&q=%40"" + _searchTerm + """);
            _connection = (HttpURLConnection) _url_obj.openConnection();
            _connection.setRequestMethod("GET");
            _connection.setRequestProperty("User-Agent", _userAgent);
            _responseCode = _connection.getResponseCode();
            BufferedReader in;
            in = new BufferedReader(new InputStreamReader(
                    _connection.getInputStream()));
            _totalResults = new StringBuffer();
            String inputLine;
            while ((inputLine = in.readLine()) != null){
                _totalResults.append(inputLine);
            }
            in.close();                
        } catch (IOException ex) {
            System.err.println(ex.getMessage());
        }
    }
}
Categories: Java Tags: , , ,
%d bloggers like this: