【发布时间】:2014-04-22 08:35:04
【问题描述】:
我一直在尝试将 Google 自定义搜索 api 用于学校作业,并且在尝试获取结果的 json 格式时遇到了一些问题,我已经在 Google 开发人员控制台和 Google 自定义上配置了所有内容搜索引擎控制面板,至少我是这么认为的。这是我的代码sn-p
String qstring = "key="+key + "&cx="+ cx +"&q="+searchtext+"&alt=json"+"&start="+"0";
String query = null;
try {
query = URLEncoder.encode(qstring, "UTF-8")
.replaceAll("\\%28", "(")
.replaceAll("\\%29", ")")
.replaceAll("\\+", "%20")
.replaceAll("\\%27", "'")
.replaceAll("\\%21", "!")
.replaceAll("\\%7E", "~");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
URL url = null;
try {
url = new URL("https://www.googleapis.com/customsearch/v1?" + query);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
HttpURLConnection conn2 = null;
try {
conn2 = (HttpURLConnection) url.openConnection();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
conn2.setRequestMethod("GET");
} catch (ProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
conn2.setRequestProperty("Accept", "application/json");
try {
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn2.getInputStream())));
String line;
while ((line = br.readLine()) != null) {
content.append(line + "\n");
}
br.close();
return content.toString();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
以及在 logcat 中显示的错误
04-22 07:26:36.253: W/System.err(4229): java.io.FileNotFoundException: https://www.googleapis.com/customsearch/v1?key%3DAIzaSyBgvvgYg3mYS66fMM9j0qpaG6wlvUc1KLk%26cx%3D008838294879486691568%3Axy_pvqrl6fa%26q%3Djava.pdf%26alt%3Djson%26start%3D0
04-22 07:26:36.289: W/System.err(4229): at libcore.net.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:186)
04-22 07:26:36.321: W/System.err(4229): at libcore.net.http.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:271)
如果我做错了什么,我将不胜感激。请帮忙!
【问题讨论】:
-
找不到文件...不言自明。您的 URL 应为:googleapis.com/customsearch/…,并读取服务器 JSON 响应
标签: android json google-custom-search