Google Custom Search in Java

by GarciaPL on Saturday 18 October 2014

When I am starting to search something using of course Google, from my point of view it is quite annoying that when you would like to exclude some search results in search bar, in way as you can see below, you can only exclude probably about 20 sites.


So, to get the most hidden results from Google, I decided to create small tool which uses Google Custom Search API.
Before you can start your journey with this very interesting API you should (see [2] in Reference) :
1) Create search engine and get it's ID 2) Generate API key for Custom Search API
After you successfully received all the necessary data from above steps, you can simply download small Java program developed by me ([3]), which can be used by you to go deeper and deeper with your searching of web!

public class WarsawDeveloperJava {
    public static void main(String[] args) throws Exception {
 
        String searchText = "Warsaw java developer";
        String key = "CUSTOM_SEARCH_API_KEY";
        String cx = "SEARCH_ENGINE_ID";
 
        JsonFactory jsonFactory = new JacksonFactory();
        HttpRequestInitializer httpRequestInitializer = new HttpRequestInitializer() {
 
            @Override
            public void initialize(HttpRequest request) throws IOException {
 
            }
        };
        Customsearch customsearch = new Customsearch(new NetHttpTransport(), jsonFactory, httpRequestInitializer);
        Customsearch.Cse.List list = customsearch.cse().list(searchText);
        list.setCx(cx);
        list.setCr("countryPL"); //country origin of search result
        list.setDateRestrict("m2"); //results should be no older than 2 months
        list.setKey(key);
 
        Search results = list.execute();
        List listResult = (List) results.getItems();
 
        Iterator iterator = listResult.iterator();
        while(iterator.hasNext()) {
            Result next = (Result)iterator.next();
            System.out.println(next.getLink());
        }
    }
}

Reference :
[1] Developers.google.com - Custom Search API
[2] Weblog4j.com - Having Fun with Google Custom Search API and Java
[3] Pastebin.com Source Code