WebService接口的生成和调用(WebService接口)

朱雀 2024-02-19 18:04 146阅读 0赞

Table of Contents

一:WebService的服务端发布

1:发布web程序服务端发布

2:本地发布

二:Webservice客户端调用:

1:本地生成代码,直接调用:

2、利用dos命令生成代码,和第一种基本一致

3:service编程实现调用

4:利用apache的AXIS直接调用远程的web service

5:HttpURLConnection调用方式

6.Ajax调用方式


Web Service是构建互联网分布式系统的基本部件,它是一个应用程序,它向外界暴露出一个能够通过Web进行调用的API。这就是说,别人能够用编程的方法通过Web来调用这个应用程序。

它通过标准通信协议,在互联网上以服务的方式发布有用的程序模块,目前大部分是用SOAP作为通信协议。

它提供一份详细的接口说明书,来帮助用户构建应用程序,这个接口说明书叫WSDL(Web服务描述语言,Web Service Description Language)。

请求报文和返回报文都是XML格式的,XML(Extensible Markup Language)即可扩展标记语言,它与HTML一样,都是SGML(Standard Generalized MarkupLanguage,标准通用标记语言)。

#

一:WebService的服务端发布

1:发布web程序服务端发布

创建 service 接口

20190228151335816.png

创建接口实现类,实现业务逻辑

watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQxNjk0OTA2_size_16_color_FFFFFF_t_70

配置 web.xml 中 中 Xfire
提供对 xfire 的拦截

watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQxNjk0OTA2_size_16_color_FFFFFF_t_70 1

配置 webservice 配置
在 class 目录下建立 META-INF 目录,如(META-INF>xfire->services.xml),在
services.xml 文件中进行 webservice 服务的发布.

watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQxNjk0OTA2_size_16_color_FFFFFF_t_70 2

然后启动服务,在浏览器中输入http://ip/项目名称/services就可以看到发布的接口了

20160818095252750

2:本地发布

  1. import javax.jws.WebMethod;
  2. import javax.jws.WebService;
  3. import javax.xml.ws.Endpoint;
  4. /**
  5. * Title: ServiceHello
  6. * Description: 基于jdk1.6以上的javax.jws 发布webservice接口
  7. @WebService - 它是一个注解,用在类上指定将此类发布成一个ws。
  8. Endpoint – 此类为端点服务类,它的方法publish用于将一个已经添加了@WebService注解
  9. 对象绑定到一个地址的端口上。
  10. * Version:1.0.0
  11. * @author panchengming
  12. */
  13. @WebService
  14. public class JwsServiceHello {
  15. /** 供客户端调用方法 该方法是非静态的,会被发布
  16. * @param name 传入参数
  17. * @return String 返回结果
  18. * */
  19. public String getValue(String name){
  20. return "欢迎你! "+name;
  21. }
  22. /**
  23. * 方法上加@WebMentod(exclude=true)后,此方法不被发布;
  24. * @param name
  25. * @return
  26. */
  27. @WebMethod(exclude=true)
  28. public String getHello(String name){
  29. return "你好! "+name;
  30. }
  31. /** 静态方法不会被发布
  32. * @param name
  33. * @return
  34. */
  35. public static String getString(String name){
  36. return "再见!"+name;
  37. }
  38. //通过EndPoint(端点服务)发布一个WebService
  39. public static void main(String[] args) {
  40. /*参数:1,本地的服务地址;
  41. 2,提供服务的类;
  42. */
  43. Endpoint.publish("http://192.168.1.105:8080/Service/ServiceHello", new JwsServiceHello());
  44. System.out.println("发布成功!");
  45. //发布成功后 在浏览器输入 http://192.168.1.105:8080/Service/ServiceHello?wsdl
  46. }
  47. }

二:Webservice客户端调用:

1:本地生成代码,直接调用:

1:新建一个class类,用于调用webservice。右键src,找到Web Service Client,并输入wsdl地址,选择下载代码的路径;

(url: http://192.168.1.105:8080/Service/ServiceHello?wsdl)

SouthEast

SouthEast 1

2.将地址上的文件下载下来(注意和发布JDK一致);
3.写调用方法调用下载下来的WebService中的java类中的方法;
示例:

  1. import com.pcm.ws.jws.JwsServiceHello;
  2. import com.pcm.ws.jws.JwsServiceHelloService;
  3. /**
  4. *
  5. * Title: JwsClientHello
  6. * Description: webService 客户端调用
  7. * Version:1.0.0
  8. * @author panchengming
  9. */
  10. public class JwsClientHello {
  11. public static void main(String[] args) {
  12. //调用webservice
  13. JwsServiceHello hello=new JwsServiceHelloService().getJwsServiceHelloPort();
  14. String name=hello.getValue("panchengming");
  15. System.out.println(name);
  16. }
  17. }

2、利用dos命令生成代码,和第一种基本一致

A、在工作空间创建用于存放使用wsimport命令生成的客户端代码的java工程

20160818100003585

B、使用jdk提供的wsimport命令生成客户端代码

20160818095348645

● wsimport命令是jdk提供的,作用是根据使用说明书生成客户端代码,wsimport只支持SOAP1.1客户端的生成

● wsimport常用参数

-d:默认参数,用于生成.class文件
-s:生成.java文件
-p:指定生成java文件的包名,不指定则为WSDL说明书中namespace值得倒写

20160818095614973

C、在doc窗口进入java工程项目的src目录,执行wsimport命令

20160818100134731

D、在Eclipse中刷新java项目,将生成的客户端代码copy到客户端工程中

20160818100248274

E、创建服务视图,类名从标签的name属性获取

20160818100530861

F、获取服务实现类,视图实例调用getProt()方法,实现类的类名从portType的name属性获取

20160818100555768

G、调用查询方法,方法名从portType下的operation标签的name属性获取

20160818100656191

  1. package com.webservice.client;
  2. import com.webservice.jaxws.WeatherServiceImpl;
  3. import com.webservice.jaxws.WeatherServiceImplService;
  4. public class Client {
  5. public static void main(String[] args) {
  6. //创建视图
  7. WeatherServiceImplService wsis = new WeatherServiceImplService();
  8. //获取服务实现类
  9. WeatherServiceImpl wsi = wsis.getPort(WeatherServiceImpl.class);
  10. //调用查询方法
  11. String weather = wsi.queryWeather("北京");
  12. System.out.println(weather);
  13. }
  14. }

20160819143145513

服务视图,webservice的服务结点,它包括了服务端点

为每个服务端点定义消息格式和协议细节

服务端点,描述 web service可被执行的操作方法,以及相关的消息,通过binding指向portType

定义一个操作(方法)的数据参数(可有多个参数)

定义 web service 使用的全部数据类型

3:service编程实现调用

注意:
(1)该种方式可以自定义关键元素,方便以后维护,是一种标准的开发方式;
(2)这种方式同样需要wsimport生成客户端代码,只不过仅需要将服务接口类引入即可,例如如果需要<wsdl:port name="MobileCodeWSSoap" binding="tns:MobileCodeWSSoap">端口服务,则需要将生成的MobileCodeWSSoap.class类引入;

(1)、开发步骤

A、wisimport生成客户端代码

B、使用serivce类创建服务视图

C、获取服务实现类

D、调用查询方法

  1. import java.io.IOException;
  2. import java.net.MalformedURLException;
  3. import java.net.URL;
  4. import javax.xml.namespace.QName;
  5. import javax.xml.ws.Service;
  6. import cn.itcast.mobile.MobileCodeWSSoap;
  7. /**
  8. *
  9. * Title: ServiceClient.java
  10. * Description:Service编程实现服务端调用
  11. * 这种方式同样需要wsimport生成客户端代码,只不过仅需要将服务接口类引入即可,例如如果需要
  12. * <wsdl:port name="MobileCodeWSSoap" binding="tns:MobileCodeWSSoap">
  13. * 端口服务,则需要将生成的MobileCodeWSSoap.class类引入
  14. */
  15. public class ServiceClient {
  16. public static void main(String[] args) throws IOException {
  17. //创建WSDL地址,不是服务地址
  18. URL url = new URL("http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx?wsdl");
  19. //创建服务名称
  20. //1.namespaceURI - 命名空间地址 (wsdl文档中的targetNamespace)
  21. //2.localPart - 服务视图名 (wsdl文档中服务名称,例如<wsdl:service name="MobileCodeWS">)
  22. QName qname = new QName("http://WebXml.com.cn/", "MobileCodeWS");
  23. //Service创建视图
  24. //参数:
  25. //1.wsdlDocumentLocation - 使用说明书地址
  26. //2.serviceName - 服务名称
  27. Service service = Service.create(url, qname);
  28. //获取服务实现类
  29. //参数解释:serviceEndpointInterface - 服务端口(wsdl文档中服务端口的name属性,例如<wsdl:port name="MobileCodeWSSoap" binding="tns:MobileCodeWSSoap">)
  30. MobileCodeWSSoap mobileCodeWSSoap = service.getPort(MobileCodeWSSoap.class);
  31. //调用查询方法
  32. String result = mobileCodeWSSoap.getMobileCodeInfo("188888888", "");
  33. System.out.println(result);
  34. }
  35. }

4:利用apache的AXIS直接调用远程的web service

  1. public static void axis() {
  2. Service service = new Service();
  3. try {
  4. Call call = (Call) service.createCall();
  5. //设置地址
  6. call.setTargetEndpointAddress("http://www.webxml.com.cn/WebServices/ValidateEmailWebService.asmx?wsdl");
  7. call.setUseSOAPAction(true);
  8. //域名加方法,//上面有写着targetNamespace="http://x.x.x/",这个就是你的命名空间值了;加方法名
  9. call.setSOAPActionURI("http://WebXml.com.cn/" + "ValidateEmailAddress");
  10. // 设置要调用哪个方法
  11. call.setOperationName(new QName("http://WebXml.com.cn/", "ValidateEmailAddress")); // 设置要调用哪个方法
  12. //设置参数名 :参数名 ,参数类型:String, 参数模式:'IN' or 'OUT'
  13. call.addParameter(new QName("http://WebXml.com.cn/", "theEmail"), // 设置要传递的参数
  14. org.apache.axis.encoding.XMLType.XSD_STRING, javax.xml.rpc.ParameterMode.IN);
  15. call.setEncodingStyle("UTF-8");
  16. //返回类型
  17. call.setReturnType(org.apache.axis.encoding.XMLType.XSD_STRING);// (标准的类型)
  18. // 调用方法并传递参数
  19. String res = String.valueOf(call.invoke(new Object[]{"wangkanglu1024@163.com"}));
  20. System.out.println(res);
  21. } catch (Exception ex) {
  22. ex.printStackTrace();
  23. }
  24. public static void axis2() throws MalformedURLException, SOAPException, ServiceException, RemoteException {
  25. String endpoint = "http://ws.webxml.com.cn/WebServices/MobileCodeWS.asmx?wsdl";
  26. String res = null;
  27. // 查询电话号码的接口方法名
  28. String operationName = "getMobileCodeInfo";
  29. // 定义service对象
  30. Service service = new Service();
  31. // 创建一个call对象
  32. Call call = (Call) service.createCall();
  33. // 设置目标地址,即webservice路径
  34. call.setTargetEndpointAddress(endpoint);
  35. // 设置操作名称,即方法名称 targetNamespace="http://WebXml.com.cn/"
  36. call.setOperationName(new QName("http://WebXml.com.cn/", operationName));
  37. // 设置方法参数
  38. call.addParameter(new QName("http://WebXml.com.cn/", "mobileCode"),
  39. org.apache.axis.encoding.XMLType.XSD_STRING,
  40. javax.xml.rpc.ParameterMode.IN);
  41. call.addParameter(new QName("http://WebXml.com.cn/", "userID"),
  42. org.apache.axis.encoding.XMLType.XSD_STRING,
  43. javax.xml.rpc.ParameterMode.IN);
  44. // 设置返回值类型
  45. //对于返回是字符串数组的返回类型只有这两种可行
  46. //call.setReturnType(org.apache.axis.encoding.XMLType.SOAP_VECTOR);
  47. call.setReturnClass(java.lang.String.class);
  48. call.setUseSOAPAction(true);
  49. call.setSOAPActionURI("http://WebXml.com.cn/" + "getMobileCodeInfo");
  50. res = (String) call.invoke(new Object[]{"15611111111", "0"});
  51. // 如果返回类型是org.apache.axis.encoding.XMLType.SOAP_VECTOR时用下面的转型接收
  52. //Vector v=(Vector) call.invoke(new Object[]{cityCode,userId});
  53. System.out.println(res);
  54. }

5:HttpURLConnection调用方式

(1)、开发步骤

A、创建服务地址

B、打开服务地址的一个连接

C、设置连接参数

● 注意

  • a、POST必须大写,如果小写会出如下异常:
  • b、如果不设置输入输出,会报异常

D、组织SOAP协议数据,发送给服务器

E、接收服务端的响应

  1. import java.io.BufferedReader;
  2. import java.io.IOException;
  3. import java.io.InputStream;
  4. import java.io.InputStreamReader;
  5. import java.io.OutputStream;
  6. import java.net.HttpURLConnection;
  7. import java.net.MalformedURLException;
  8. import java.net.URL;
  9. /**
  10. *
  11. * @ClassName: HttpURLConectionMode
  12. * @Description: TODO(通过HttpURLConnection发送http请求)
  13. * sope协议,比较麻烦的是需要拼接xml格式的请求数据
  14. * @author
  15. * @date 2017年11月8日 上午9:18:24
  16. *
  17. */
  18. public class HttpClient {
  19. public static void main(String[] args) throws IOException {
  20. //第一步:创建服务地址,不是WSDL地址
  21. URL url = new URL("http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx");
  22. //2:打开到服务地址的一个连接
  23. HttpURLConnection connection = (HttpURLConnection) url.openConnection();
  24. //3:设置连接参数
  25. //3.1设置发送方式:POST必须大写
  26. connection.setRequestMethod("POST");
  27. //3.2设置数据格式:Content-type
  28. connection.setRequestProperty("content-type", "text/xml;charset=utf-8");
  29. //3.3设置输入输出,新创建的connection默认是没有读写权限的,
  30. connection.setDoInput(true);
  31. connection.setDoOutput(true);
  32. //4:组织SOAP协议数据,发送给服务端
  33. String soapXML = getXML("1866666666");
  34. OutputStream os = connection.getOutputStream();
  35. os.write(soapXML.getBytes());
  36. //5:接收服务端的响应
  37. int responseCode = connection.getResponseCode();
  38. if(200 == responseCode){//表示服务端响应成功
  39. InputStream is = connection.getInputStream();
  40. InputStreamReader isr = new InputStreamReader(is);
  41. BufferedReader br = new BufferedReader(isr);
  42. StringBuilder sb = new StringBuilder();
  43. String temp = null;
  44. while(null != (temp = br.readLine())){
  45. sb.append(temp);
  46. }
  47. System.out.println(sb.toString());
  48. is.close();
  49. isr.close();
  50. br.close();
  51. }
  52. os.close();
  53. }
  54. /**
  55. * <?xml version="1.0" encoding="utf-8"?>
  56. <soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
  57. <soap:Body>
  58. <getMobileCodeInfo xmlns="http://WebXml.com.cn/">
  59. <mobileCode>string</mobileCode>
  60. <userID>string</userID>
  61. </getMobileCodeInfo>
  62. </soap:Body>
  63. </soap:Envelope>
  64. * @param phoneNum
  65. * @return
  66. */
  67. public static String getXML(String phoneNum){
  68. String soapXML = "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  69. +"<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">"
  70. +"<soap:Body>"
  71. +"<getMobileCodeInfo xmlns=\"http://WebXml.com.cn/\">"
  72. +"<mobileCode>"+phoneNum+"</mobileCode>"
  73. +"<userID></userID>"
  74. +"</getMobileCodeInfo>"
  75. +" </soap:Body>"
  76. +"</soap:Envelope>";
  77. return soapXML;
  78. }
  79. }

提供一个比较完善一点的工具类

  1. public Map<String, Object> webServiceRequestUtil(String requesturl, String soapXML) throws IOException, ZycxException {
  2. HttpURLConnection connection = null;
  3. OutputStream os = null;
  4. Map<String, Object> reslut = new HashMap<>();
  5. try {
  6. //1:创建服务地址
  7. URL url = new URL(requesturl);
  8. //2:打开到服务地址的一个连接
  9. connection = (HttpURLConnection) url.openConnection();
  10. //3:设置连接参数
  11. //3.1设置发送方式:POST必须大写
  12. connection.setRequestMethod("POST");
  13. //3.2设置数据格式:Content-type
  14. connection.setRequestProperty("content-type", "text/xml;charset=utf-8");
  15. //3.3设置输入输出,新创建的connection默认是没有读写权限的,
  16. connection.setDoInput(true);
  17. connection.setDoOutput(true);
  18. //4:组织SOAP协议数据,发送给服务端
  19. os = connection.getOutputStream();
  20. os.write(soapXML.getBytes());
  21. } catch (IOException e) {
  22. throw new myException("链接webservice出错!url为:" + requesturl + ";exception:" + e);
  23. }
  24. StringBuilder sb = new StringBuilder();
  25. InputStream is = null;
  26. InputStreamReader isr = null;
  27. BufferedReader br = null;
  28. try {
  29. String temp = null;
  30. //5:接收服务端的响应
  31. int responseCode = connection.getResponseCode();
  32. if (200 == responseCode) {//表示服务端响应成功
  33. is = connection.getInputStream();
  34. isr = new InputStreamReader(is);
  35. br = new BufferedReader(isr);
  36. while ((temp = br.readLine()) != null) {
  37. sb.append(temp);
  38. }
  39. //这是我自己封装了一个map的返回格式,封装了headr和body
  40. reslut = ReturnUtil.returnjSON(BackStatus.BACK_STATUS_OK, "success", sb.toString());
  41. } else {
  42. is = connection.getInputStream();
  43. isr = new InputStreamReader(is);
  44. br = new BufferedReader(isr);
  45. while ((temp = br.readLine()) != null) {
  46. sb.append(temp);
  47. }
  48. reslut = ReturnUtil.returnjSON(BackStatus.BACK_STATUS_EXCEPTION + "", "请求出错,http响应为:"+responseCode, sb.toString());
  49. }
  50. } catch (IOException e) {
  51. throw new myException("返回结果解析出错" + e);
  52. } finally {
  53. if(!Objects.isNull(br)){
  54. br.close();
  55. }
  56. if(!Objects.isNull(isr)){
  57. isr.close();
  58. }
  59. if(!Objects.isNull(is)){
  60. is.close();
  61. }
  62. if(!Objects.isNull(os)){
  63. os.close();
  64. }
  65. }
  66. return reslut;
  67. }

6.Ajax调用方式

  1. <!doctype html>
  2. <html lang="en">
  3. <head>
  4. <title>Ajax调用方式</title>
  5. <script type="text/javascript">
  6. function queryMobile(){
  7. //创建XMLHttpRequest对象
  8. var xhr = new XMLHttpRequest();
  9. //打开链接
  10. xhr.open("post","http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx",true);
  11. //设置content-type
  12. xhr.setRequestHeader("content-type","text/xml;charset=utf-8");
  13. //设置回调函数
  14. xhr.onreadystatechange=function(){
  15. //判断客户端发送成功&&服务端响应成功
  16. if(4 == xhr.readyState && 200 == xhr.status){
  17. alert(xhr.responseText);
  18. }
  19. }
  20. //组织SOAP协议数据
  21. var soapXML = "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  22. +"<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">"
  23. +"<soap:Body>"
  24. +"<getMobileCodeInfo xmlns=\"http://WebXml.com.cn/\">"
  25. +"<mobileCode>"+document.getElementById("phoneNum").value+"</mobileCode>"
  26. +"<userID></userID>"
  27. +"</getMobileCodeInfo>"
  28. +" </soap:Body>"
  29. +"</soap:Envelope>";
  30. alert(soapXML);
  31. //发送请求
  32. xhr.send(soapXML);
  33. }
  34. </script>
  35. </head>
  36. <body>
  37. 手机号归属地查询:<input type="text" id="phoneNum" /><input type="button" value="查询" onclick="javascript:queryMobile();"/>
  38. </body>
  39. </html>

参考文章:java调用webservice接口 几种方法_yesIcando-bupt的博客-CSDN博客_java 调webservice接口

整理至此,希望对大家有帮助

发表评论

表情:
评论列表 (有 0 条评论,146人围观)

还没有评论,来说两句吧...

相关阅读