2

我使用 Google Cloud Platform 免费试用 https://cloud.google.com/free-trial/

在我的 java 应用程序中使用自定义搜索 API

我在我的应用程序中编写了以下代码

 URL url = new URL("https://www.googleapis.com/customsearch/v1?key="+key+ 
 "&cx=013036536707430787589:_pqjad5hr1a&q="+ qry + "&alt=json");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
BufferedReader br = new BufferedReader(new InputStreamReader(
        (conn.getInputStream())));

String output;
System.out.println("Output from Server .... \n");

while ((output = br.readLine()) != null) {

    if(output.contains("\"link\": \"")){                
        String link=output.substring(output.indexOf("\"link\": \"")+("\"link\": \"").length(), output.indexOf("\","));

        System.out.println(link);       //Will print the google search links
    }     
}
conn.disconnect();       

有时它给了我一个结果,然后它给了我以下错误,并且无论查询字符串如何都会发生此错误

线程“主”java.io.IOException 中的异常:服务器返回 HTTP 响应代码:403 用于 URL:https ://www.googleapis.com/customsearch/v1?key=????&cx=013036536707430787589:_pqjad5hr1a&q= ?? ???在 sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1839) 在 sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1440) 在 sun.net.www.protocol .https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:254)

请问问题出在哪里?

4

1 回答 1

0

403特别是谷歌的禁止错误 - 这意味着您发送太多请求太快,他们认为您使用机器人或自动化

如果您在浏览器中加载该查询并查看请求 - 继续快速刷新,直到您看到一个 html 响应说

We're sorry...

... but your computer or network may be sending automated queries. To protect our users, we can't process your request right now.

See Google Help for more information.
于 2017-09-05T20:54:42.010 回答