2011-08-02 42 views

回答

2

以下示例基于1-1.30 client lib。由于没有太多的文件,这绝对不是最好的例子。事实上,我故意使用已弃用的方法来设置API密钥,因为更新的方式看起来过于复杂。

假设你已经包含在项目的构建路径正确的罐子依赖,一个基本的例子是:

//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 

你需要得到一个自定义搜索引擎ID,并从Google API Console API密钥

4

我想在这里进行更正。

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<Result> items = results.getItems(); 

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

     } 

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

“API_KEY”和“CUSTOM_SEARCH_ENGINES”的值是什么?谢谢 –

+0

对于搜索引擎ID - setCx()函数 - 转到https://www.google.com/cse/all,创建并选择一个自定义搜索引擎,然后单击“搜索引擎ID”按钮。 – Tom

0

试试Google REST/JSON API:see API Guide。使用它很容易,只要你有你的引擎ID和钥匙。您只需使用您选择的库正确构建URL并使用响应JSON解析搜索结果即可。