Java google custom search api

I am trying to use the java client for a custom Google search but could not find sample tutorials on the Internet. Can someone provide a simple example for me to get started? Thanks!

+6
source share
4 answers

I want to make a correction here.

customsearch.setKey("YOUR_API_KEY_GOES_HERE"); 

does not work for lib 1.6 client, but later works

  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(); } 
+4
source

The following example is based on 1-1.30 client lib . Since there is not much documentation, this is definitely not the best example. In fact, I intentionally use an outdated method to set the API key, since the newer method seemed too complicated.

Assuming you have included the correct jar dependencies in the project build path, a basic example might 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 will need to get the user search engine identifier and API key from the Google API Console

+2
source

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

+1
source

Try the Google REST / JSON api: see the API Guide . It is very easy to work with it if you have your engine ID and key. All you have to do is build the URL correctly and parse the search results from the JSON response using the library of your choice.

0
source

Source: https://habr.com/ru/post/894140/


All Articles