Ajax基礎 (八)

4.8 訪問Web服務

         Web服務---支持異構計算機系統相互操作的一種有用的工具。

         最著名的Web服務實現是SOAP(簡單對象訪問協議),是XML協議;

         WSDLWeb服務描述語言)文檔也是XML文檔,描述如何創建Web服務的客戶。

         WSDLSOAP通常一同使用。SOAP是一個很難使用的技術,只有在跨平臺互操作性確實是一個很重要的需求是纔會使用。

         REST(代表狀態傳輸)是一種實現Web服務更簡單的方法。

         Yahoo!使用REST作爲其公共的Web服務的協議。

         XMLHttpRequest對象只能訪問發起文檔(即調用腳本)所在域中的資源。安全限制(訪問其他域的資源失敗。)

         方法:建立Yahoo!的網關,它與XMLHttpRequest腳本在同一域中,由網關接收來自XMLHttpRequest對象的請求,並把它轉發到Yahoo!Web服務。Yahoo!做出響應返回結果時,網關再把結果路由傳送到瀏覽器。(好處:更加健壯,可以擴展網關,讓它支持其他的Web服務提供者)

         RESTSOAP比較:

         都把響應返回爲XML文檔,最顯著的差異是:REST將請求作爲帶查詢串參數的簡單URL發送,而SOAP請求時具體的XML文檔,通常通過POST而不是GET方法發送。

(使用一個XMLHttpRequest請求從網站加載靜態XML文檔,文檔是SOAP請求的模板,加載後,使用JavaScript DOM方法修改模板,使只滿足特定的請求,之後,再用第二個XMLHttpRequest請求發送新創建的SOAP請求。)

         注意:

                   發送中參數名queryresults都是YahooSearch API定義的。

                   返回中TitleSummaryClickUrl ,Url都是Yahoo!返回帶的tagname.

                            分別表示標題,簡介,實際UrlUrl鏈接。

         代碼中的難點:

                   服務器方面---載入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);
    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章