如何获取Google搜索结果'使用ajax API的代码段?

时间:2014-10-13 12:17:08

标签: ajax google-api code-snippets

我使用StackOverflow中的一个示例代码来获取搜索结果'标题,网址和摘要:

for (int s = 0; s < 20; s = s + 4)
{
    String address = "http://ajax.googleapis.com/ajax/services/search/web?v=1.0&start=" + s + "&q=";
    String query = "ucd";
    String charset = "UTF-8";

    URL url = new URL(address + URLEncoder.encode(query, charset));
    Reader reader = new InputStreamReader(url.openStream(), charset);
    GoogleSearch results = new Gson().fromJson(reader, GoogleSearch.class);

    for (int i = 0; i < 4; i++)
    {
        System.out.println("Title: " + results.getResponseData().getResults().get(i).getTitle().replaceAll("<b>", "").replaceAll("</b>", ""));

        System.out.println("URL: " + results.getResponseData().getResults().get(i).getUrl());

        System.out.println("Snippet: " + results.getResponseData().getResults().get(i).getSnippet() + "\n");

        System.out.println(results.getResponseData().getResults().get(i));
    }
}

但似乎http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=不会从搜索中返回代码段。

使用Google API获取此功能的其他任何方式?搜索后无法找到...

1 个答案:

答案 0 :(得分:1)

使用方法getContent()而不是getSnippet()。例如:

System.out.println("Snippet: " + results.getResponseData().getResults().get(i).getContent() + "\n");