java google custom search api

我正在尝试将Java客户端用于Google自定义搜索API,但无法在网上找到任何示例教程。 有人能为我提供一个简单的例子吗? 谢谢!

我想在这里进行修正。

customsearch.setKey("YOUR_API_KEY_GOES_HERE"); 

不适用于客户端lib 1.6但以下工作

  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 items = results.getItems(); for(Result result:items) { System.out.println("Title:"+result.getHtmlTitle()); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } 

以下示例基于1-1.30客户端lib 。 由于没有太多文档,这绝对不是最好的例子。 事实上,我故意使用不推荐使用的方法来设置API密钥,因为较新的方式似乎过于复杂。

假设您在项目的构建路径中包含了正确的jar依赖项,那么基本示例如下:

 //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 items = results.getItems(); //now go do something with your list of Result objects 

您需要从Google API控制台获取自定义搜索引擎ID和API密钥

这是一个关于如何创建谷歌自定义搜索引擎并在java程序中使用它的简单演示http://preciselyconcise.com/apis_and_installations/search_google_programmatically.php

试用Google REST / JSON API: 请参阅API指南 。 只要您拥有引擎ID和密钥,就可以轻松使用它。 您所要做的就是正确构建URL并使用您选择的库从响应JSON中解析搜索结果。