4.8 访问Web服务
Web服务---支持异构计算机系统相互操作的一种有用的工具。
最著名的Web服务实现是SOAP(简单对象访问协议),是XML协议;
WSDL(Web服务描述语言)文档也是XML文档,描述如何创建Web服务的客户。
WSDL和SOAP通常一同使用。SOAP是一个很难使用的技术,只有在跨平台互操作性确实是一个很重要的需求是才会使用。
REST(代表状态传输)是一种实现Web服务更简单的方法。
Yahoo!使用REST作为其公共的Web服务的协议。
XMLHttpRequest对象只能访问发起文档(即调用脚本)所在域中的资源。安全限制(访问其他域的资源失败。)
方法:建立Yahoo!的网关,它与XMLHttpRequest脚本在同一域中,由网关接收来自XMLHttpRequest对象的请求,并把它转发到Yahoo!Web服务。Yahoo!做出响应返回结果时,网关再把结果路由传送到浏览器。(好处:更加健壮,可以扩展网关,让它支持其他的Web服务提供者)
REST与SOAP比较:
都把响应返回为XML文档,最显著的差异是:REST将请求作为带查询串参数的简单URL发送,而SOAP请求时具体的XML文档,通常通过POST而不是GET方法发送。
(使用一个XMLHttpRequest请求从网站加载静态XML文档,文档是SOAP请求的模板,加载后,使用JavaScript DOM方法修改模板,使只满足特定的请求,之后,再用第二个XMLHttpRequest请求发送新创建的SOAP请求。)
注意:
发送中参数名query和results都是Yahoo!Search API定义的。
返回中Title,Summary,ClickUrl ,Url都是Yahoo!返回带的tagname.
分别表示标题,简介,实际Url,Url链接。
代码中的难点:
服务器方面---载入java.net.HttpURLConnection包和java.net.URL包。
Yahoo!网关地址:YAHOO_SEARCH_URL=
http://api.search.yahoo.com/WebSearchService/V1/webSearch?”+”appid=your_app_id”
+”&type=all”;
BufferedReader, OutputStream, resposneOutput.write(input.getBytes());
示例:
Web端:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Yahoo! Search Web Services</title>
<script type="text/javascript">
var xmlHttp;
function createXMLHttpRequest() {
if (window.ActiveXObject) {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
else if (window.XMLHttpRequest) {
xmlHttp = new XMLHttpRequest();
}
}
function doSearch() {
var url = "YahooSearchGateway?" + createQueryString() + "&ts=" + new Date().getTime();
createXMLHttpRequest();
xmlHttp.onreadystatechange = handleStateChange;
xmlHttp.open("GET", url, true);
xmlHttp.send(null);
}
function createQueryString() {
var searchString = document.getElementById("searchString").value;
searchString = escape(searchString);
var maxResultsCount = document.getElementById("maxResultCount").value;
var queryString = "query=" + searchString + "&results=" + maxResultsCount;
return queryString;
}
function handleStateChange() {
if(xmlHttp.readyState == 4) {
if(xmlHttp.status == 200) {
parseSearchResults();
}
else {
alert("Error accessing Yahoo! search");
}
}
}
function parseSearchResults() {
var resultsDiv = document.getElementById("results");
while(resultsDiv.childNodes.length > 0) {
resultsDiv.removeChild(resultsDiv.childNodes[0]);
}
var allResults = xmlHttp.responseXML.getElementsByTagName("Result");
var result = null;
for(var i = 0; i < allResults.length; i++) {
result = allResults[i];
parseResult(result);
}
}
function parseResult(result) {
var resultDiv = document.createElement("div");
var title = document.createElement("h3");
title.appendChild(document.createTextNode(getChildElementText(result, "Title")));
resultDiv.appendChild(title);
var summary = document.createTextNode(getChildElementText(result, "Summary"));
resultDiv.appendChild(summary);
resultDiv.appendChild(document.createElement("br"));
var clickHere = document.createElement("a");
clickHere.setAttribute("href", getChildElementText(result, "ClickUrl"));
clickHere.appendChild(document.createTextNode(getChildElementText(result, "Url")));
resultDiv.appendChild(clickHere);
document.getElementById("results").appendChild(resultDiv);
}
function getChildElementText(parentNode, childTagName) {
var childTag = parentNode.getElementsByTagName(childTagName);
return childTag[0].firstChild.nodeValue;
}
</script>
</head>
<body>
<h1>Web Search Using Yahoo! Search Web Services</h1>
<form action="#">
Search String: <input type="text" id="searchString"/>
<br/><br/>
Max Number of Results:
<select id="maxResultCount">
<option value="1">1</option>
<option value="10">10</option>
<option value="25">25</option>
<option value="50">50</option>
</select>
<br/><br/>
<input type="button" value="Submit" οnclick="doSearch();"/>
</form>
<h2>Results:</h2>
<div id="results"/>
</body>
</html>
Server端:
package ajaxbook.chap4;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import javax.servlet.*;
import javax.servlet.http.*;
public class YahooSearchGatewayServlet extends HttpServlet {
private static final String YAHOO_SEARCH_URL =
"http://api.search.yahoo.com/WebSearchService/V1/webSearch?appid=thunderboltsoftware"
+ "&type=all";
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String url = YAHOO_SEARCH_URL + "&" + request.getQueryString();
HttpURLConnection con = (HttpURLConnection)new URL(url).openConnection();
con.setDoInput(true);
con.setDoOutput(true);
con.setRequestMethod("GET");
//Send back the response to the browser
response.setStatus(con.getResponseCode());
response.setContentType("text/xml");
BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String input = null;
OutputStream responseOutput = response.getOutputStream();
while((input = reader.readLine()) != null) {
responseOutput.write(input.getBytes());
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
}