google custom search使用(二)

之前已经对于Google Custom Search Engine做了一番介绍,接下来我们看一下如何使用。


我们做一个简单的例子演示如何使用Google Custom Search Engine:

  1. 首先你需要一个自定义的搜索引擎,可以访问http://www.google.com/cse进行定制和增加,我们可以在建立的搜索引擎的Control Panel中得到唯一标示符,这里我得到的是:xxxxxxxxxxx,这个值将会用来做我们的cx参数值;
  2. 其次你还需要一个应用的ID,这个值可以在https://code.google.com/apis/console的API Access面板中的API key:xxxxx,这个值会作为我们的key的参数值;
  3. 接着我们可以构造我们的请求了,具体参见下面的代码;
	private static final int RESULT_OK = 200;
	private static final int BUF_SIZE = 1024 * 8; // 8k

	public static void main(String[] args) {
		// API key
		String strKey = "AIzaSyBKmmLBxKXaZpIdDcdyIZDJA6_yrN-ejHI";
		// Unique ID
		String strID = "012004925040627705852:rsqwwhrqtr0"; 
		int strStart = 11;
		int num = 1;
		String strQ = "花";
		/**
		 *  这里提供了如何使用请求的例子
		 *  https://developers.google.com/custom-search/v1/using_rest
		 *  注意以下几个参数:
		 *  标准参数:
		 *  alt,可选参数json, atom,用于指定返回值格式,默认值是json
		 *  callback,JavaScript回调函数
		 *  prettyPrint,返回内容是否采用便于人类阅读的格式,默认值是true
		 *  API自定义参数:
		 *  cx,CSE的唯一标识符
		 *  num,搜索结果个数,可选值1~10,默认为10
		 *  q,搜索表达式
		 *  safe,可选值high(开启搜索结果最高安全级别过滤)、medium(开启中等级别安全过滤)、off(关闭安全过滤)
		 *  searchType,可选值image,如果未设置,返回值将被限定为网页
		 */
		String strRequest = "https://www.googleapis.com/customsearch/v1?key=%key%&cx=%id%&q=%q%&searchType=image&start=%start%&num=%num%";
		strRequest = strRequest.replace("%key%", strKey).replace("%id%", strID).replace("%q%", strQ).replace("%start%", String.valueOf(strStart)).replace("%num%", Integer.toBinaryString(num));
		
		HttpURLConnection conn = null;
		String result = "";
		try {
			URL url = new URL(strRequest);
			conn = (HttpURLConnection) url.openConnection();
			// 使用GET方法
			conn.setRequestMethod("GET");
			int resultCode = conn.getResponseCode();
			if (resultCode == RESULT_OK) {
				InputStream is = conn.getInputStream();
				result = readAsString(is);
				is.close();
			}
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			conn.disconnect();
		}
		
		System.out.println(result);
	}

	/**
	 * 将输出内容转换为字符串形式
	 * @param ins
	 * @return
	 * @throws IOException
	 */
	public static String readAsString(InputStream ins) throws IOException {
		ByteArrayOutputStream outs = new ByteArrayOutputStream();
		byte[] buffer = new byte[BUF_SIZE];
		int len = -1;
		try {
			while ((len = ins.read(buffer)) != -1) {
				outs.write(buffer, 0, len);
			}
		} finally {
			outs.flush();
			outs.close();
		}
		return outs.toString();
	}




以上代码运行后我们能够得到查询结果,这个结果下一节我们将尝试放置到我们自己的web应用中。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值