最近工作不是很忙,利用業餘時間學習了google的文檔。Google對外提供的API功能十分強大,由於篇幅有限,這裏僅說一下Google Custom Search API。這個api提供了搜索的功能,可以搜索圖片和文字信息,並以Json的形式返回結果。我們在實際開發中無需引入任何Jar包,僅需調用google的服務即可,非常的好用,下面我會以一個demo項目的形式。
首先Google的東西,當然要看一手的官方文檔。
翻譯如下:谷歌定製搜索API可以爲web程序或桌面程序通過編程的方式提供檢索和展現的功能,使用谷歌定製搜索API,你就可以使用RESTful架構的請求網站搜索或者圖片搜索,結果以JSON或Atom的格式返回。 PS:默認返回JSON格式
翻譯如下:通過調用API,用戶的請求對應訂製搜索引擎的實例,因此,在使用這個API之前,你需要生成一個ID,在谷歌官網ControlPanel中的Setup > Basics > Details獲取這個ID)
值得注意的是,我看到很多文章提到需要拿到一個api key,老版本確實需要一個key,但是現在的googlecustom search api 已經不需要apikey了。
好了,以上準備工作就緒,下面就開始開發一個DemoProject了。
第一步:申請一個Google帳號並登錄,創建一個自己的項目,自定義一個搜索引擎實例。拿到 ID(作爲cs參數)。
第二步:新建一個Web Project。定義幾個bean,其中包括文字索引查詢結果類SearchResultItem類,圖片查詢結果類SearchResultImage類,查詢結果類SearchResult類,圖片類Image。
在此由於篇幅有限,bean的相關代碼不貼上來了。(如果需要可以下面給我留言)
第三步:寫一個servlet,做查詢動作,並把結果返回回頁面
package google.custom.search.api.servlet;
import google.custom.search.api.bean.Image;
import google.custom.search.api.bean.SearchResult;
import google.custom.search.api.bean.SearchResultItem;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.google.gson.Gson;
/**
* Author:wangjian
*/
public class GoogleCustomSearchAPIServlet extends HttpServlet {
// 最大返回結果數
private static final int RESULT_OK = 200;
// 8KB
private static final int BUF_SIZE = 1024 * 8;
// 自定義搜索引擎的ID
private static final String ID = "010589607068358538435:p8ot8fmvira";
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);
}
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.google.com:443/cse/publicurl?cx="
+ ID
+ "&q=%queryExpression%&searchType=image&start=%start%&num=%num%";
strRequest = strRequest.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);
// 設置返回JSON內容
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();
}
}
第四步:將查詢結果返回到前臺頁面:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>csdn網站即時搜索</title>
<script type="text/javascript" src="../jquery/jquery-1.8.2.js"></script>
<script type="text/javascript">
$(function(){
$("#search").click(function(){
$.post("/GoogleCustomSearchAPIServlet",
{"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>
<div id="searchbox" style="width:80%;display:block;margin:0 auto;">
<input type="text" name="field" id="field" style="width:100%;height:50px;margin-top:50px;font-size:40px;" οnkeyup="sendQuery();" />
</div>
<div id="main-content">
<div id="cse_g" style="margin:20px;"></div>
</div>
<div><script>
//在Google網站上自定義一個搜索引擎(搜索www.csdn.net的內容,返回一個一段HTML頁面代碼,用於查詢和返回結果)
(function() {
var cx = '010589607068358538435:p8ot8fmvira';
var gcse = document.createElement('script');
gcse.type = 'text/javascript';
gcse.async = true;
gcse.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') +
'//www.google.com/cse/cse.js?cx=' + cx;
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(gcse, s);
})();
</script>
<gcse:search></gcse:search></div>
<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>