我使用 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)
请问问题出在哪里?