【发布时间】:2011-10-18 13:44:59
【问题描述】:
我正在尝试使用java client for the Google custom search api 但在网上找不到任何示例教程。有人可以提供一个简单的例子让我开始吗?谢谢!
【问题讨论】:
标签: java search google-api-java-client
我正在尝试使用java client for the Google custom search api 但在网上找不到任何示例教程。有人可以提供一个简单的例子让我开始吗?谢谢!
【问题讨论】:
标签: java search google-api-java-client
我想在这里更正一下。
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();
}
【讨论】:
API_KEY 和 CUSTOM_SEARCH_ENGINES 的值是多少?谢谢
以下示例基于1-1.30 client 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<Result> items = results.getItems();
//now go do something with your list of Result objects
您需要从 Google API Console 获取自定义搜索引擎 ID 和 API 密钥
【讨论】:
这是一个关于如何创建谷歌自定义搜索引擎并从java程序http://preciselyconcise.com/apis_and_installations/search_google_programmatically.php使用它的简单演示
【讨论】:
试试 Google REST / JSON api:see API Guide。只要您有引擎 ID 和密钥,使用它就非常容易。您所要做的就是正确构建 URL 并使用您选择的库从响应 JSON 中解析搜索结果。
【讨论】: