您的位置:首页 > 编程语言 > Java开发

JAVA调用Google Custom Search API

2015-03-05 10:43 417 查看
本篇主要是通过goAgent调用Google Custom Search API,访问结果以JSON的数据结构进行返回。

提示:因为google被墙的原因,访问之前需要设置代理服务器,目前国内比较流行的就是免费的goAgent代理,虽然只有1G的流量,是可以满足单纯的网页访问的。在程序中调用API的时候,也是用的goAgent。本地服务器地址及端口号为127.0.0.1:8087(goAgent的配置方法省略)

文档原文:https://developers.google.com/custom-search/docs/tutorial/creatingcse

1、创建Custom Search Engine 的两种方式

1)使用Control Panel(最简单的方法)

2)创建引擎定义的XML文件

2、在Control Panel中创建搜索引擎

1)首先必须有google账号,登陆进入Control Panel

2)Sites to search,加入任何搜索引擎想要包含的网页(个人的或公共的),如下所示



3)为搜索引擎命名,设置搜索引擎的语言

4)高级选项,使用Schema.org类型来限制网页,也就是返回的网页是包含Shcema.org类型的。(可以不设置)

Schema.org类型的理解

问题一:那什么是Schema.org呢?

首先我们来看一下它的发起人是:Bing, Google, Yahoo! 和 Yandex 在内的搜索引擎巨头。

目的:create and support a common set of schemas for structured data markup on web pages将为网页上的结构化数据标记建立并提供一套通用模式。Schema.org旨在成为网站站长的一站式资源,方便他们为自己的网页添加标记,以帮助各搜索引擎更好地了解他们的网站。(就是一种使用在HTML5中的内容标记语言)。Schema.org规定最基本的元素是Thing。只要你的网站提供的是一个Thing就可以用结构化数据进行描述。

例如,使用 schema.org 模式和微数据来标记一部电影与其导演。

<div itemscope itemtype="http://schema.org/Movie">//Thing开始了,定义一个itemscope,itemtype的属性是一个url
<h1 itemprop="name">Avatar</h1>//定义各个属性信息,各属性信息的内容与itemprop的内容相一致
<div itemprop="director" itemscope itemtype="http://schema.org/Person">
Director: <span itemprop="name">James Cameron</span>
(born <time itemprop="birthDate" datetime="1954-08-16">August 16, 1954</time>)
</div>
<span itemprop="genre">Science fiction</span>
<a href="../movies/avatar-theatrical-trailer.html" itemprop="trailer">Trailer</a>
</div>


作用:当你在搜索引擎中输入你想查找的信息的时候,服务器响应,将相关信息呈现到客户端,但是以什么样的方式显示呢?它可能是毫无逻辑的文字。那么Schema.org帮助浏览器以一种非常结构化的方式呈现我们的搜索结果。如下所示,显示了图片,简介等多种信息。



在这里我们先简要的理解一下schema.org的类型

需要进一步理解的点击如下链接:

(1)、http://schema.org.cn/docs/schemas.html

(2)、http://www.chinaz.com/web/2011/0722/201296.shtml

(3)、http://maxket.com/seo%E5%92%8C%E7%BB%93%E6%9E%84%E5%8C%96%E6%95%B0%E6%8D%AE/

5)点击create,成功创建。



(1)Get code生成的javascript可以直接嵌入到你的网页中,进行搜索。(因为我希望自己用JAVA处理返回的数据,这一步,我们得到一个重要的参数,即cx的值)

6)在https://console.developers.google.com中新建项目,新建项目后点击左侧的APIs&auth



7)首先点击APIs,Enabled APIs的是Custom Search API



8)然后点击Credentials,create new key,


我们得到的另一个重要的参数是API Key

3、API的使用方法

1)、通过指定的URL发送请求
https://www.googleapis.com/customsearch/v1?parameters
example:

GET https://www.googleapis.com/customsearch/v1?key=INSERT_YOUR_API_KEY&cx=017576662512468239146:omuauf_lfve&q=lectures
key:指的是API Key,通过key来找到你的应用程序

cx:指定你要搜索的搜索引擎,这里就是刚刚我们创建搜索引擎得到的

q:指定你要搜索的关键词

其他的参数信息访问https://developers.google.com/custom-search/json-api/v1/using_rest

2)、通过访问该URL,返回数据结果,JSON(默认格式)或Atom

3)、用Gson解释返回结果,并显示

4、用goAgent代理访问Google API

编写如下代码:

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class test
{
public static void main(String[] args) throws Exception
{
String strKey="AIzyAEZi1dM2WaZnpn.......";
String strID="005138399682225........";
int num=1;
String strQuery="lectures";
String str="https://www.googleapis.com/customsearch/v1?key="+strKey+"&cx="+strID+"&num="+num+"&q="+strQuery;
URL myURL = new URL(str);
HttpURLConnection conn = (HttpURLConnection) myURL.openConnection();
InputStream is=conn.getInputStream();
InputStreamReader isr=new InputStreamReader(is);
BufferedReader br=new BufferedReader(isr);
StringBuffer buffer=new StringBuffer();
String line=null;
while(null!=(line=br.readLine()))
{
buffer.append(line);
}
br.close();
isr.close();
is.close();
System.out.println(buffer);
}
}
出现错误:Connection timed out:connect



也就是说不能访问到该API

1)运行goAgent代理,

在代码的前面添加如下,配置访问通过goAgent代理

Properties systemProperties = System.getProperties();
systemProperties.setProperty("http.proxyHost", "127.0.0.1");
systemProperties.setProperty("http.proxyPort", "8087");
systemProperties.setProperty("https.proxyHost", "127.0.0.1");
systemProperties.setProperty("https.proxyPort", "8087");
systemProperties.setProperty("socksProxyHost", "127.0.0.1");
systemProperties.setProperty("socksProxyPort", "8087");
System.setProperty("sun.net.client.defaultConnectTimeout", String.valueOf(900000));
又出现错误了。

错误如下:unable to find valid certification path to requested target



原因是进行https连接时出现的无有效证书的错误。

解决该错误的两种方法:

1)下载安全证书并导入

2)进行无信任证书连接,自己实现对网站证书的免验证通过

方法一:暂略

方法二:采用实现X509TrustManager接口方法

public static void main(String[] args) throws Exception
{
<span style="color:#FF0000;">HostnameVerifier hv = new HostnameVerifier() {
public boolean verify(String urlHostName, SSLSession session) {
return true;
}
};
Properties systemProperties = System.getProperties();
systemProperties.setProperty("http.proxyHost", "127.0.0.1");
systemProperties.setProperty("http.proxyPort", "8087");
systemProperties.setProperty("https.proxyHost", "127.0.0.1");
systemProperties.setProperty("https.proxyPort", "8087");
systemProperties.setProperty("socksProxyHost", "127.0.0.1");
systemProperties.setProperty("socksProxyPort", "8087");
System.setProperty("sun.net.client.defaultConnectTimeout", String.valueOf(900000));
String strKey="AIzaSyAEZi1dM2WaZnpnD9LBRUVuBnNEK6PeTYg";
String strID="005981383996822259382:xjb1-dnz5xs";
int num=1;
String strQuery="lectures";
String str="https://www.googleapis.com/customsearch/v1?key="+strKey+"&cx="+strID+"&num="+num+"&q="+strQuery;
URL myURL = new URL(str);
<span style="color:#FF0000;">trustAllHttpsCertificates();
HttpsURLConnection.setDefaultHostnameVerifier(hv);</span>
HttpURLConnection conn = (HttpURLConnection) myURL.openConnection();
InputStream is=conn.getInputStream();
InputStreamReader isr=new InputStreamReader(is);
BufferedReader br=new BufferedReader(isr);
StringBuffer buffer=new StringBuffer();
String line=null;
while(null!=(line=br.readLine()))
{
buffer.append(line);
}
br.close();
isr.close();
is.close();
System.out.println(buffer);
}
<span style="color:#FF0000;">private static void trustAllHttpsCertificates() throws Exception {
javax.net.ssl.TrustManager[] trustAllCerts = new javax.net.ssl.TrustManager[1];
javax.net.ssl.TrustManager tm = new miTM();
trustAllCerts[0] = tm;
javax.net.ssl.SSLContext sc = javax.net.ssl.SSLContext
.getInstance("SSL");
sc.init(null, trustAllCerts, null);
javax.net.ssl.HttpsURLConnection.setDefaultSSLSocketFactory(sc
.getSocketFactory());
}

static class miTM implements javax.net.ssl.TrustManager,
javax.net.ssl.X509TrustManager {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}

public boolean isServerTrusted(
java.security.cert.X509Certificate[] certs) {
return true;
}

public boolean isClientTrusted(
java.security.cert.X509Certificate[] certs) {
return true;
}

public void checkServerTrusted(
java.security.cert.X509Certificate[] certs, String authType)
throws java.security.cert.CertificateException {
return;
}

public void checkClientTrusted(
java.security.cert.X509Certificate[] certs, String authType)
throws java.security.cert.CertificateException {
return;
}
}
最后返回json数据。

参考链接:Java安全通信:HTTPS与SSL
                    unable to find valid certification path to requested target错误解决方法:SunCertPathBuilderException:
unable to find valid certification path to requested target
                    http://www.tuicool.com/articles/zUjiIb
                    http://www.iteye.com/topic/1134798
                    Google Custom Search API博客
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  google custom search