我开始在 java 中使用谷歌自定义搜索 api,但它只是没有连接。我正在从谷歌接收 json 数据。(我应该但它没有连接..:()
HttpResponse response = httpClient.execute(httpGet);
// exception is thrown at this point.
这是我的代码中的一行。代码是:
public class MyGoogleSearch{
final static String searchURL = "https://www.googleapis.com/customsearch/v1?";
// This is Important :
final static String apiKey = "My-Key-has a '-'";
final static String customSearchEngineKey = "My-Custom-search-engine-that-has a ':' too";
public String makeSearchString(String qSearch){
String toSearch = searchURL + "key=" + apiKey + "&cx=" + customSearchEngineKey;
toSearch += "&q=" + qSearch + "&alt=json";
return toSearch;
}
public static void main(String[] argv) throws IOException{
System.setProperty("proxyHost", "my-host");
System.setProperty("proxyPort","my-Port");
MyGoogleSearch browser = new MyGoogleSearch();
String toSearch = browser.makeSearchString("flower");
System.out.println(toSearch);
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(toSearch);
HttpResponse response = httpClient.execute(httpGet);
// exception is thrown here.
HttpEntity entity = response.getEntity();
if(entity != null){
InputStream inStream = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(inStream));
int length = 0;
byte[] buffer = new byte[2048];
while((length = inStream.read(buffer)) != -1)
System.out.println(buffer);
String inputLine;
while((inputLine = reader.readLine()) != null)
System.out.println(inputLine);
}
}
}
// 错误是:
Exception in thread "main" org.apache.http.conn.HttpHostConnectException: Connection to https://www.googleapis.com refused at
org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:158)
……
Caused by: java.net.ConnectException: Connection timed out: connect
at java.net.PlainSocketImpl.socketConnect(Native Method)
这是有效的方法吗?我还没有进行任何类型的 UTF-8 编码。那会是个问题吗?
在本页面:
http://code.google.com/apis/customsearch/v1/getting_started.html
以下是 JSON/Atom 自定义搜索 API 的工作原理示例,该 API 在测试自定义搜索引擎中搜索讲座:
// 这是仅适用于 javaScript 还是适用于 java
但是,我将自定义搜索引擎密钥放在 cx 上,这应该是正确的
我去了google api explorer https://code.google.com/apis/explorer/
我在填写程序时选择自定义搜索并填写 *q 和 cx 列:
它显示了结果并 GET https://www.googleapis.com/customsearch/v1?q=o&cx= {MY-Custom-Search-Engine-No}&pp=1&key={YOUR_API_KEY}
但这次 cx 值在 ':' 字符的位置有 %3。
我将如何对我的键和 cse-no 中的所有字符执行此操作