google custom search使用(三)

下面我们来看一个实际案例:

首先我们建立一个servlet,代码如下:


搜索结果的图片类定义


public class SearchResultImage {
//    "contextLink": "http://zh.wikipedia.org/wiki/%E8%8A%B1",
//    "height": 188,
//    "width": 250,
//    "byteSize": 24465,
//    "thumbnailLink": "https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcQU2J6pZj2kHhl39Z5bjndI1RJXgb7Jbx1xLV7kc2crbt9VbFoJiUDJlQ",
//    "thumbnailHeight": 83,
//    "thumbnailWidth": 111
	public String contextLink;
	public int height;
	public int width;
	public int byteSize;
	public String thumbnailLink;
	public int thumbnailHeight;
	public int thumbnailWidth;
}

搜索结果的item定义

package com.freesoft.model.gcs;

public class SearchResultItem {
	public String kind;
	public String title;
	public String htmlTitle;
	public String link;
	public String displayLink;
	public String snippet;
	public String htmlSnippet;
	public String mime;
	public SearchResultImage image;
//	"kind": "customsearch#result",
//	   "title": "花- 维基百科,自由的百科全书",
//	   "htmlTitle": "\u003cb\u003e花\u003c/b\u003e- 维基百科,自由的百科全书",
//	   "link": "http://upload.wikimedia.org/wikipedia/commons/thumb/8/84/Plum_flowers.jpg/250px-Plum_flowers.jpg",
//	   "displayLink": "zh.wikipedia.org",
//	   "snippet": "花- 维基百科,自由的百科全书",
//	   "htmlSnippet": "\u003cb\u003e花\u003c/b\u003e- 维基百科,自由的百科全书",
//	   "mime": "image/jpeg",
//	   "image": {
//	   }
}

搜索结果定义



import com.google.gson.JsonObject;

public class SearchResult {
	// 多余的字段可以不要
	private String kind;
	private JsonObject url;
	private JsonObject queries;
	private JsonObject context;
	private JsonObject searchInformation;
	// 这是我们需要的字段
	private SearchResultItem items[];
	
	public String getKind() {
		return kind;
	}
	public JsonObject getUrl() {
		return url;
	}
	public JsonObject getQueries() {
		return queries;
	}
	public JsonObject getContext() {
		return context;
	}
	public JsonObject getSearchInformation() {
		return searchInformation;
	}
	public SearchResultItem[] getItems() {
		return items;
	}
	public void setKind(String kind) {
		this.kind = kind;
	}
	public void setUrl(JsonObject url) {
		this.url = url;
	}
	public void setQueries(JsonObject queries) {
		this.queries = queries;
	}
	public void setContext(JsonObject context) {
		this.context = context;
	}
	public void setSearchInformation(JsonObject searchInformation) {
		this.searchInformation = searchInformation;
	}
	public void setItems(SearchResultItem[] items) {
		this.items = items;
	}
	

}

输出的类型定义


public class Image {
	// 标题
	private String title;
	// 图片地址
	private String link;
	// 分享网站
	private String displayLink;
	
	public Image(String title, String link, String displayLink) {
		super();
		this.title = title;
		this.link = link;
		this.displayLink = displayLink;
	}
	public String getTitle() {
		return title;
	}
	public void setTitle(String title) {
		this.title = title;
	}
	public String getLink() {
		return link;
	}
	public void setLink(String link) {
		this.link = link;
	}
	public String getDisplayLink() {
		return displayLink;
	}
	public void setDisplayLink(String displayLink) {
		this.displayLink = displayLink;
	}
}

Servlet定义

import com.google.gson.Gson;

public class GCSServlet extends HttpServlet {
	private static final long serialVersionUID = -1275024561023110262L;
	private static final int RESULT_OK = 200;
	private static final int BUF_SIZE = 1024 * 8; // 8k
	private static final String API_KEY = "AIzaSyBKmmLBxKXaZpIdDcdyIZDJA6_yrN-ejHI"; // API
																						// key
	private static final String UNIQUE_ID = "012004925040627705852:rsqwwhrqtr0"; // Unique
																					// ID

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		handle(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		handle(request, response);
	}

	/**
	 * 
	 * 这里提供了如何使用请求的例子 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,如果未设置,返回值将被限定为网页
	 * 
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	private void handle(HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		int start = Integer.parseInt(request.getParameter("start"));
		int num = Integer.parseInt(request.getParameter("num"));
		String queryExpression = request.getParameter("queryexpression");
		String strRequest = "https://www.googleapis.com/customsearch/v1?key=%API_KEY%&cx=%UNIQUE_ID%&q=%queryExpression%&searchType=image&start=%start%&num=%num%";
		strRequest = strRequest.replace("%API_KEY%", API_KEY)
				.replace("%UNIQUE_ID%", UNIQUE_ID)
				.replace("%queryExpression%", queryExpression)
				.replace("%start%", String.valueOf(start))
				.replace("%num%", Integer.toString(num));

		HttpURLConnection conn = null;
		String queryResult = null;
		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();
				queryResult = readAsString(is);
				is.close();
			} else {
				System.out.println("Fault on getting http result, code: " + resultCode);
			}
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			conn.disconnect();
		}

		if ((queryResult != null) && (queryResult.length() != 0)) {
			String respStr = parseResult(queryResult);
			System.out.println(respStr);

			// 设置返回内容
			response.setContentType("application/json; charset=utf-8");
			// 设置不缓存内容
			response.setHeader("pragma", "no-cache");
			response.setHeader("cache-control", "no-cache");
			PrintWriter writer = response.getWriter();
			writer.write(respStr);
			writer.flush();
			writer.close();
		}
	}

	/**
	 * 将搜索结果字符串转化为需要的对象列表
	 * 
	 * @param queryResult
	 * @return
	 */
	private String parseResult(String queryResult) {
		Gson gson = new Gson();
		SearchResult e = gson.fromJson(queryResult, SearchResult.class);
		System.out.println(queryResult);
		SearchResultItem items[] = e.getItems();
		Image images[] = new Image[items.length];
		for (int i = 0; i < items.length; i++) {
			images[i] = new Image(items[i].title, items[i].link, items[i].displayLink);
		}
		return gson.toJson(images);
	}

	/**
	 * 将输出内容转换为字符串形式
	 * 
	 * @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();
	}

}


用来测试的html页面


<!DOCTYPE html>
<html>
  <head>
	<meta charset="utf-8">
    <title>jQuery ajax test</title>
	
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="this is my page">
    <meta http-equiv="content-type" content="text/html; charset=UTF-8">
    
    <!--<link rel="stylesheet" type="text/css" href="./styles.css">-->
    <script type="text/javascript" src="../jquery/jquery-1.8.2.js"></script>
    <script type="text/javascript">
	$(function(){
		$("#search").click(function(){
				$.post("/GCSServlet.action", 
					{"start": $("#start").val(), "num": $("#num").val(), "queryexpression": $("#queryexpression").val()}, 
					function(data, status){						
						var html = "<table style='width: 960px; border: 1px solid black;'>";
						for(var i = 0; i < data.length; i++){
							if (i % 3 == 0)
								html += "<tr>";
							var image = data[i];
							var title = image.title;
							var link = image.link;
							var displayLink = image.displayLink;
							html += "<td style='width: 320px'>" + title + "<img src='" + link + "' width='320px' height='240px'>" + displayLink + "</td>";
							
							if (i % 3 == 2)
								html += "</tr>";
						}
						html += "</table>";
						$("table:eq(0)").remove();
						$("#resultArea").append(html);
					});
		});
	});
    	
    </script>

  </head>
  
  <body>
  <label for="queryexpression">搜索内容</label>
  <input type="text" id="queryexpression">
  <label for="start">从第几个结果开始</label>
  <input type="text" id="start">
  <label for="num">搜索多少结果</label>
  <input type="text" id="num">
  <input type="button" id="search" value="搜索">
  
  <div id="resultArea"></div>
  </body>
</html>





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
### 回答1: Custom WaveView 是一个自定义的波形视图,可以用于显示音频波形、心电图、脑电图等信号的波形。使用 Custom WaveView 需要以下步骤: 1. 在布局文件中添加 Custom WaveView 控件。 2. 在代码中获取 Custom WaveView 控件的实例。 3. 设置 Custom WaveView 的属性,如波形颜色、线条宽度、背景颜色等。 4. 调用 Custom WaveView 的 setWaveData 方法,传入波形数据。 5. 调用 Custom WaveView 的 startAnim 方法,开始绘制波形。 6. 在需要停止绘制波形时,调用 Custom WaveView 的 stopAnim 方法。 7. 在需要清空波形时,调用 Custom WaveView 的 clearWaveData 方法。 8. 在需要重新设置波形数据时,调用 Custom WaveView 的 setWaveData 方法。 以上就是 Custom WaveView 的使用教程,具体实现可以参考官方文档或相关示例代码。 ### 回答2: Custom WaveView是一种可用于任何制波器管道的插件,可用于生成简单线性波浪,高级动态线性波浪,曲线波浪和噪声波浪的形状和颜色。以下是Custom WaveView使用教程。 1. 安装和设置Custom WaveView插件 首先,您需要在您的电脑上安装并启用Custom WaveView插件,然后将其添加到您的工作区或工具栏中。一旦你把插件拖到你的制波器管道上,你就可以开始制作你的自定义波浪。 2. 创建自定义波浪 Custom WaveView的界面非常直观和简单,您可以通过选择基础波浪类型和编辑选项来轻松地创建您自己的自定义波浪。您可以选择线性波浪,动态线性波浪,曲线波浪和噪声波浪等不同的波浪类型。然后,您可以调整曲线的点数,波长和振幅,以及将它们旋和平铺。 3. 编辑颜色和渐变 一旦您选择了您想要的波浪类型和形状,您可以进一步编辑颜色和渐变,以使您的波浪看起来更可定制化和吸引人。通过选择渐变的类型和色彩范围,您可以为您的波浪添加任何配色和过渡效果。 4. 预览和导出波浪 当您满意您制作的波浪时,您可以通过预览选项和导出选项,查看和保存您的波浪。您可以通过预览选项预览您的波浪,并且可以在不同的屏幕分辨率下查看它的外观效果。同时,您可以导出波浪到您的计算机以备将来使用。 总之,Custom WaveView是一个功能强大且易于使用的插件,可用于生成各种形状和类型的自定义波浪。只要您使用正确的步骤和工具来制作您的波浪,您可以创建非常好的波浪。 ### 回答3: Custom WaveView是一款功能强大的软件,它可以为您创建自定义的波形视图。以下是Custom WaveView的使用教程。 第一步:下载和安装Custom WaveView软件。 您可以从官方网站或其他可靠的网站下载Custom WaveView软件,并按照指示进行安装。 第二步:打开Custom WaveView软件。 当您打开Custom WaveView软件时,您将看到一个空白的波形视图界面。 第步:创建自定义波形。 在Custom WaveView软件中,您可以通过多种途径创建自定义波形。您可以使用内置的波形生成器,也可以导入外部的音频文件。您还可以通过调整波形参数来自定义波形的形状和大小。您可以自由选择颜色、频率和振幅,以满足您个性化的需求。 第四步:保存自定义波形。 在Custom WaveView软件中,您可以将创建的自定义波形保存为图片文件,例如JPEG、PNG或BMP格式。您还可以将波形传输到其他应用程序,例如Photoshop或Adobe Premiere Pro。 第五步:添加自定义波形到您的项目中。 您可以在您的项目中使用Custom WaveView软件创建的波形,例如添加到您的音视频文件中,或将其作为游戏特效。 综上所述,Custom WaveView是一款非常实用的软件,它可以帮助您创建自定义波形视图。如果您需要创建自定义波形视图,请尝试使用Custom WaveView。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值