3

我来自这个问题

以下代码不能正常工作:

public static void main(String[] args) throws Exception {
    for (int i = 0; i < 15; i++)
    {
        String google = "http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=";
        String search = "test";
        String charset = "UTF-8";

        URL url = new URL(google + URLEncoder.encode(search, charset));
        Reader reader = new InputStreamReader(url.openStream(), charset);
        GoogleResults results = new Gson().fromJson(reader, GoogleResults.class);

        // Show title and URL of 1st result.
        System.out.println(results.getResponseData().getResults().get(0).getTitle());
        System.out.println(results.getResponseData().getResults().get(0).getUrl());
    }
}

如果我运行一次搜索查询就可以正常工作,但是在这个循环中我得到一个空指针异常。

不幸的是,我需要我的程序进行几个查询:(我该怎么办?

NullPointerException它首先返回 a results.getResponseData

4

2 回答 2

2

发生这种情况是因为 Google 主动阻止了可疑的服务滥用条款。请参阅此处的第 5.3 节:

http://www.google.com/accounts/TOS

如果 Google 检测到您在未经他们同意的情况下通过程序发出搜索请求,他们不会发回结果。您的 JSON 响应将包含以下内容:

{"responseData": null, "responseDetails": "Suspected Terms of Service Abuse. Please see http://code.google.com/apis/errors", "responseStatus": 403}
于 2011-11-16T17:43:25.077 回答
0

在使用它们之前检查以确保results其他包含的对象不存在。null

if ((results != null) && (results.getResponseData() != null) &&
    (results.getResponseData().getResults() != null) &&
    (results.getResponseData().getResults().get(0) != null)) {
    // Show title and URL of 1st result.
    System.out.println(results.getResponseData().getResults().get(0).getTitle());
    System.out.println(results.getResponseData().getResults().get(0).getUrl());
}
于 2011-11-16T16:09:12.217 回答