<%@page contentType="text/html"%> <%@page pageEncoding="UTF-8"%> <%@page import="java.io.*,java.net.URL,javax.xml.xpath.*,org.w3c.dom.*,org.xml.sax.InputSource,java.net.URLEncoder"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Yahoo Search</title> </head> <body> <h1>Yahoo Search</h1> <form action="index.jsp"> Enter search string : <input type=text name=pattern value="${param.pattern}"> <input type=submit value="Search"/> </form> <% String pattern = request.getParameter("pattern"); if ( pattern == null) return; String appid = ""; // use URLEncoder to encode search pattern - it is required. String yrequest = "http://search.yahooapis.com/WebSearchService/V1/webSearch?appid=YahooDemo&query=" + URLEncoder.encode(pattern,"UTF-8") + "&results=5"; try { URL url = new URL(yrequest); InputStream in = url.openStream(); XPathFactory x = XPathFactory.newInstance(); XPath path = x.newXPath(); // take data that comes from service invocation InputSource source = new InputSource(in); NodeList nl = (NodeList) path.evaluate("//urn:yahoo:srch:Result", source, XPathConstants.NODESET); if ( nl.getLength() == 0 ) out.println("<h3>Sorry! No Match Found!</h3>"); else for ( int i = 0 ; i < nl.getLength(); i ++) { Element e = (Element) nl.item(i); out.println("<a href=" + e.getChildNodes().item(2).getTextContent() + ">" + e.getChildNodes().item(0).getTextContent() + "</a><p/>"); } // end of for } catch (Exception e) { out.println("<h3>" + e.getMessage() + "</h3>"); } %> </body> </html>