标签:
前些天去南京参加中国软件杯比赛的时候看到有些队伍在获取学校的数据时用到了WebService,感觉挺实用,自己趁着周末也入门了一下。
首先自己先创建一个WebService工程。这里我使用了Web项目来发布WebService。
下面是项目源码的结构:
其中WebServiceAction是一个servlet类,用来发布WebService。util包有两个工具类,BusQueryService是WebService的主要类,这里提供的是公交信息查询的服务。
要成为WebService,需要再类上加入@WebService注解,注解的参数看个人喜欢设置(也可以不设置)。
下面是BusQueryService的源码:
1 package itc10.ws; 2 3 import java.util.List; 4 5 import javax.jws.WebParam; 6 import javax.jws.WebResult; 7 import javax.jws.WebService; 8 9 import org.dom4j.Document; 10 import org.dom4j.Element; 11 12 import itc10.util.HttpUtil; 13 import itc10.util.StringUtil; 14 /** 15 * 公交信息WebService.包含公交线信息查询和公交站信息查询 16 * @author ITC10 17 */ 18 @WebService(
serviceName = "busQueryWS",
portName = "busQueryPort",
name = "busQuery",
targetNamespace = "itc10.ws"
) 19 public class BusQueryService { 20 21 private static final String LINE_URL = "http://openapi.aibang.com/bus/lines"; 22 private static final String STATE_URL = ""; 23 private static final String KEY = "7d3dbe746b8673****84ddb6a3da27f1"; 24 25 // 公交线查询 26 public @WebResult(name = "lineInfo") String queryLine( 27 @WebParam(name = "city") String city, 28 @WebParam(name = "line") String line) { 29 30 if (city == null || "".equals(city)) { 31 return "--参数city不能为空--"; 32 } 33 if (line == null || "".equals(line)) { 34 return "--参数line不能为空--"; 35 } 36 37 StringBuffer url = new StringBuffer(); 38 url.append(LINE_URL).append("?app_key=").append(KEY) 39 .append("&city=").append(HttpUtil.encodeURL(city)) 40 .append("&q=").append(HttpUtil.encodeURL(line)); 41 // 发送HTTP请求查询 42 System.out.println(this.getClass().toString()
+ "---URL---"+ url.toString() + "---"); 43 String result = HttpUtil.get(url.toString()); 44 Document doc = StringUtil.string2Doc(result); 45 46 // 解析请求 47 Element root = doc.getRootElement(); 48 Element lines = root.element("lines"); 49 // 获取所有线路 50 @SuppressWarnings("unchecked") 51 List<Element> lineList = lines.elements("line"); 52 StringBuffer sb = new StringBuffer(); 53 // 获取前面两条线路 54 for (int i = 0; i < 2; i++) { 55 sb.append(lineList.get(i).element("name")
.getText() + "<br><br>") 56 .append(lineList.get(i).element("info").getText()
.replace("|", "<br>").replace(";", "<br>") + "<br><br>") 57 .append(lineList.get(i).element("stats").getText()
.replace(";", " --> ")); 58 } 59 // 截掉最后的 "-->" 60 sb = new StringBuffer(sb.subSequence(0, sb.toString().length() - 2)); 61 return sb.toString(); 62 } 63 64 // 公交站查询 65 public String queryState(String city, String state) { 66 return ""; 67 } 68 }
这里的公交信息查询用的是爱帮的接口,KEY是在爱帮申请的,这里我将其部分隐藏了。
LINE_URL 是查询公交线的接口,该接口需要3个参数。
第一个参数是key,是爱帮提供给开发者的,第二个参数是city,是城市的名称,第三个参数是q,是公交的名称。
这个类用到了2个工具类,HttpUtil (发送Http请求),StringUtil(将String转成Document对象)
下面是HttpUtil的源码(这里用到的Apache的httpclient):
1 package itc10.util; 2 3 import java.net.URLEncoder; 4 5 import org.apache.commons.httpclient.HttpClient; 6 import org.apache.commons.httpclient.methods.GetMethod; 7 8 public class HttpUtil { 9 10 private HttpUtil(){} 11 12 public static String get(String url) { 13 String result = null; 14 try { 15 HttpClient http = new HttpClient(); 16 GetMethod method = new GetMethod(url); 17 http.executeMethod(method); 18 result = method.getResponseBodyAsString(); 19 method.releaseConnection(); 20 } catch (Exception e) { 21 throw new RuntimeException(e); 22 } 23 return result; 24 } 25 26 public static String encodeURL (String url) { 27 try { 28 url = URLEncoder.encode(url, "utf-8"); 29 } catch (Exception e) { 30 throw new RuntimeException(e); 31 } 32 return url; 33 } 34 }
StringUtil.java
package itc10.util; import java.io.StringReader; import org.dom4j.Document; import org.dom4j.io.SAXReader; import org.xml.sax.InputSource; public class StringUtil { private StringUtil(){} public static Document string2Doc (String src) { StringReader sReader = new StringReader(src); InputSource is = new InputSource(sReader); SAXReader saxReader = new SAXReader(); Document doc = null; try { doc = saxReader.read(is); } catch (Exception e) { throw new RuntimeException(e); } return doc; } }
WebSerivce功能写完,接下的就是要发布它了。
这里我使用Servlet来发布这个WebService。在Servlet的init()发布WebService。
并在web.xml设置项目启动就启动这个Servlet.
BusQueryAction.java
1 package itc10.servlet; 2 3 import java.io.IOException; 4 import java.util.Date; 5 6 import javax.servlet.ServletConfig; 7 import javax.servlet.ServletException; 8 import javax.servlet.http.HttpServlet; 9 import javax.servlet.http.HttpServletRequest; 10 import javax.servlet.http.HttpServletResponse; 11 import javax.xml.ws.Endpoint; 12 13 import itc10.ws.BusQueryService; 14 15 /** 16 * Servlet implementation class WebServiceAction 17 */ 18 public class WebServiceAction extends HttpServlet { 19 private static final long serialVersionUID = 1L; 20 21 @Override 22 public void init(ServletConfig config) throws ServletException { 23 System.out.println("--- start BusQueryService at " + new Date().toString() + " ---"); 24 StringBuffer url = new StringBuffer(); 25 url = url.append(config.getInitParameter("prefix")) 26 .append(":") 27 .append(config.getInitParameter("port")) 28 .append(config.getInitParameter("ctx")) 29 .append("/ws"); 30 System.out.println("---" + url + " ---"); 31 Endpoint.publish(url.toString(), new BusQueryService()); 32 } 33 34 /** 35 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse 36 * response) 37 */ 38 protected void doGet(HttpServletRequest request, HttpServletResponse response) 39 throws ServletException, IOException { 40 } 41 42 /** 43 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse 44 * response) 45 */ 46 protected void doPost(HttpServletRequest request, HttpServletResponse response) 47 throws ServletException, IOException { 48 } 49 50 }
web.xml
1 <?xml version="1.0" encoding="UTF-8"?> 2 <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 3 xmlns="http://java.sun.com/xml/ns/javaee" 4 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" 5 id="WebApp_ID" version="2.5"> 6 <display-name>web_service</display-name> 7 <welcome-file-list> 8 <welcome-file>index.jsp</welcome-file> 9 </welcome-file-list> 10 11 <servlet> 12 <servlet-name>WebServiceAction</servlet-name> 13 <servlet-class>itc10.servlet.WebServiceAction</servlet-class> 14 <init-param> 15 <param-name>prefix</param-name> 16 <param-value>http://192.168.1.103</param-value> 17 </init-param> 18 <init-param> 19 <param-name>port</param-name> 20 <param-value>8090</param-value> 21 </init-param> 22 <init-param> 23 <param-name>ctx</param-name> 24 <param-value>/web_service</param-value> 25 </init-param> 26 <load-on-startup>0</load-on-startup> 27 </servlet> 28 29 </web-app>
这里使用servlet参数来设置webService的各个参数。
最后拼凑成的URL为:http://192.168.1.103:8090/web_service/ws
最后把项目发布到Tomcat,访问:http://192.168.1.103:8090/web_service/ws?wsdl 就可以看到webService的WSDL信息了。
标签:
原文地址:http://www.cnblogs.com/itc10/p/4770921.html