开发者

java google custom search api

I'm trying to use the java cl开发者_开发问答ient for the Google custom search api but couldn't find any sample tutorials on the web. Can someone provide a simple example for me to get started? Thank you!


I want to make a correction here.

customsearch.setKey("YOUR_API_KEY_GOES_HERE");

does not work for client lib 1.6 but following does work

     Customsearch customsearch = new Customsearch(new NetHttpTransport(), new JacksonFactory());

    try {
        com.google.api.services.customsearch.Customsearch.Cse.List list = customsearch.cse().list("YOUR_SEARCH_STRING_GOES_HERE");
        list.setKey("YOUR_API_KEY_GOES_HERE");
        list.setCx("YOUR_CUSTOM_SEARCH_ENGINE_ID_GOES_HERE");
        Search results = list.execute();
        List<Result> items = results.getItems();

        for(Result result:items)
        {
            System.out.println("Title:"+result.getHtmlTitle());

        }

    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }


The following example is based on the 1-1.30 client lib. As there isn't much documentation this is definitely not the best example. In fact I'm intentionally using a deprecated method to set the API key as the newer way seemed overly complex.

Assuming you have included the correct jar dependencies in your project's build path, a basic example would be:

//Instantiate a Customsearch object with a transport mechanism and json parser    
Customsearch customsearch = new Customsearch(new NetHttpTransport(), new JacksonFactory());
//using deprecated setKey method on customsearch to set your API Key
customsearch.setKey("YOUR_API_KEY_GOES_HERE");
//instantiate a Customsearch.Cse.List object with your search string
com.google.api.services.customsearch.Customsearch.Cse.List list = customsearch.cse().list("YOUR_SEARCH_STRING_GOES_HERE");
//set your custom search engine id
list.setCx("YOUR_CUSTOM_SEARCH_ENGINE_ID_GOES_HERE")
//execute method returns a com.google.api.services.customsearch.model.Search object
Search results = list.execute();
//getItems() is a list of com.google.api.services.customsearch.model.Result objects which have the items you want
List<Result> items = results.getItems();
//now go do something with your list of Result objects

You'll need to get a custom search engine id, and an API key from the Google API Console


Here is a simple demo on how to create a google custom search engine and use it from a java program http://preciselyconcise.com/apis_and_installations/search_google_programmatically.php


Try Google REST / JSON api: see API Guide. It is very easy to work with it, as long as you have your engine id and key. All you have to do is properly construct the URL and parse the search results out of response JSON using a library of your choice.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜