用JAX-WS(Java API for XML Web Services)调用WebService不需要引入其他框架,都是JDK自带的;文中所使用到的软件版本:Java 1.8.0_191、Dom4j 2.1.1。

1、准备

参考Java调用WebService方法总结(1)--准备工作

2、调用

2.1、Dispatch方式

Dispatch又有Payload方式和Message两种方式。

2.1.1、Payload方式

在payload方式中,只需传入SOAP消息中的body部分。

/**
* dispatch Payload方式调用WebService
* @param portName 端口名称
* @param param 参数
*/
public static void dispatchPayload(String portName, String param) {
try {
StringBuffer source = new StringBuffer();
source.append("<web:toTraditionalChinese xmlns:web=\"" + targetNamespace + "\">");
source.append("<web:sText>").append(param).append("</web:sText>");
source.append("</web:toTraditionalChinese>");
StreamSource xmlSource = new StreamSource(new StringReader(source.toString())); URL wsdlURL = new URL(url);
QName serviceQName = new QName(targetNamespace, "TraditionalSimplifiedWebService");
Service service = Service.create(wsdlURL, serviceQName);
QName portQName = new QName(targetNamespace, portName);
Dispatch<Source> dispatch = service.createDispatch(portQName, Source.class, Service.Mode.PAYLOAD); //.NET的服务端Soap1.1需要,不加会报错误:服务器未能识别 HTTP 头 SOAPAction 的值
Map<String, Object> requestContext = dispatch.getRequestContext();
requestContext.put(BindingProvider.SOAPACTION_USE_PROPERTY, Boolean.TRUE);
requestContext.put(BindingProvider.SOAPACTION_URI_PROPERTY, "http://webxml.com.cn/toTraditionalChinese"); Source orderSource = dispatch.invoke(xmlSource);
StreamResult result = new StreamResult(new ByteArrayOutputStream());
Transformer trans = TransformerFactory.newInstance().newTransformer();
trans.transform(orderSource, result);
ByteArrayOutputStream baos = (ByteArrayOutputStream) result.getOutputStream();
String responseContent = new String(baos.toByteArray());
System.out.println(responseContent); Reader file = new StringReader(responseContent);
SAXReader reader = new SAXReader();
Document dc = reader.read(file);
Element root = dc.getRootElement();
String r = root.elementText("toTraditionalChineseResult").trim();
System.out.println(r); } catch (Exception e) {
e.printStackTrace();
}
}

2.1.2、Message方式

在Message方式中,需传入整个Soap消息。

/**
* dispatch Payload方式调用WebService
* @param soapNamespace soap消息整个消息体的命名空间,Soap1.1和Soap1.2不一样
* @param portName 端口名称
* @param param 参数
*/
public static void dispatchMessage(String soapNamespace, String portName, String param) {
try {
StringBuffer source = new StringBuffer();
source.append("<soapenv:Envelope xmlns:soapenv=\"" + soapNamespace + "\" xmlns:web=\"" + targetNamespace + "\">");
source.append("<soapenv:Header/>");
source.append("<soapenv:Body>");
source.append("<web:toTraditionalChinese>");
source.append("<web:sText>").append(param).append("</web:sText>");
source.append("</web:toTraditionalChinese>");
source.append("</soapenv:Body>");
source.append("</soapenv:Envelope>");
StreamSource xmlSource = new StreamSource(new StringReader(source.toString())); URL wsdlURL = new URL(url);
QName serviceQName = new QName(targetNamespace, "TraditionalSimplifiedWebService");
Service service = Service.create(wsdlURL, serviceQName);
QName portQName = new QName(targetNamespace, portName);
Dispatch<Source> dispatch = service.createDispatch(portQName, Source.class, Service.Mode.MESSAGE); //.NET的服务端Soap1.1需要,不加会报错误:服务器未能识别 HTTP 头 SOAPAction 的值
Map<String, Object> requestContext = dispatch.getRequestContext();
requestContext.put(BindingProvider.SOAPACTION_USE_PROPERTY, Boolean.TRUE);
requestContext.put(BindingProvider.SOAPACTION_URI_PROPERTY, "http://webxml.com.cn/toTraditionalChinese"); Source orderSource = dispatch.invoke(xmlSource);
StreamResult result = new StreamResult(new ByteArrayOutputStream());
Transformer trans = TransformerFactory.newInstance().newTransformer();
trans.transform(orderSource, result);
ByteArrayOutputStream baos = (ByteArrayOutputStream) result.getOutputStream();
String responseContent = new String(baos.toByteArray());
System.out.println(responseContent); Reader file = new StringReader(responseContent);
SAXReader reader = new SAXReader();
Document dc = reader.read(file);
//节点名称为toTraditionalChineseResult 命名空间为http://webxml.com.cn/
String r = dc.selectSingleNode("//*[local-name()='toTraditionalChineseResult' and namespace-uri()='http://webxml.com.cn/']").getText().trim();
System.out.println(r);
} catch (Exception e) {
e.printStackTrace();
}
}

2.1.3、完整代码

代码中的设置的信息都可以在准备工作中查询到,或WSDL中或Soap消息中,这里就不一一解释了。完整代码如下:

package com.inspur.ws;

import java.io.ByteArrayOutputStream;
import java.io.Reader;
import java.io.StringReader;
import java.net.URL;
import java.util.Map; import javax.xml.namespace.QName;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import javax.xml.ws.BindingProvider;
import javax.xml.ws.Dispatch;
import javax.xml.ws.Service; import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader; /**
* JAX-WS Dispatch方式调用WebService样例
* @author wuyy
*
*/
public class JaxWsDispatch {
private static String url = "http://www.webxml.com.cn/WebServices/TraditionalSimplifiedWebService.asmx?wsdl";
private static String targetNamespace = "http://webxml.com.cn/";
/**
* dispatch Payload方式调用WebService
* @param portName 端口名称
* @param param 参数
*/
public static void dispatchPayload(String portName, String param) {
try {
StringBuffer source = new StringBuffer();
source.append("<web:toTraditionalChinese xmlns:web=\"" + targetNamespace + "\">");
source.append("<web:sText>").append(param).append("</web:sText>");
source.append("</web:toTraditionalChinese>");
StreamSource xmlSource = new StreamSource(new StringReader(source.toString())); URL wsdlURL = new URL(url);
QName serviceQName = new QName(targetNamespace, "TraditionalSimplifiedWebService");
Service service = Service.create(wsdlURL, serviceQName);
QName portQName = new QName(targetNamespace, portName);
Dispatch<Source> dispatch = service.createDispatch(portQName, Source.class, Service.Mode.PAYLOAD); //.NET的服务端Soap1.1需要,不加会报错误:服务器未能识别 HTTP 头 SOAPAction 的值
Map<String, Object> requestContext = dispatch.getRequestContext();
requestContext.put(BindingProvider.SOAPACTION_USE_PROPERTY, Boolean.TRUE);
requestContext.put(BindingProvider.SOAPACTION_URI_PROPERTY, "http://webxml.com.cn/toTraditionalChinese"); Source orderSource = dispatch.invoke(xmlSource);
StreamResult result = new StreamResult(new ByteArrayOutputStream());
Transformer trans = TransformerFactory.newInstance().newTransformer();
trans.transform(orderSource, result);
ByteArrayOutputStream baos = (ByteArrayOutputStream) result.getOutputStream();
String responseContent = new String(baos.toByteArray());
System.out.println(responseContent); Reader file = new StringReader(responseContent);
SAXReader reader = new SAXReader();
Document dc = reader.read(file);
Element root = dc.getRootElement();
String r = root.elementText("toTraditionalChineseResult").trim();
System.out.println(r); } catch (Exception e) {
e.printStackTrace();
}
} /**
* dispatch Payload方式调用WebService
* @param soapNamespace soap消息整个消息体的命名空间,Soap1.1和Soap1.2不一样
* @param portName 端口名称
* @param param 参数
*/
public static void dispatchMessage(String soapNamespace, String portName, String param) {
try {
StringBuffer source = new StringBuffer();
source.append("<soapenv:Envelope xmlns:soapenv=\"" + soapNamespace + "\" xmlns:web=\"" + targetNamespace + "\">");
source.append("<soapenv:Header/>");
source.append("<soapenv:Body>");
source.append("<web:toTraditionalChinese>");
source.append("<web:sText>").append(param).append("</web:sText>");
source.append("</web:toTraditionalChinese>");
source.append("</soapenv:Body>");
source.append("</soapenv:Envelope>");
StreamSource xmlSource = new StreamSource(new StringReader(source.toString())); URL wsdlURL = new URL(url);
QName serviceQName = new QName(targetNamespace, "TraditionalSimplifiedWebService");
Service service = Service.create(wsdlURL, serviceQName);
QName portQName = new QName(targetNamespace, portName);
Dispatch<Source> dispatch = service.createDispatch(portQName, Source.class, Service.Mode.MESSAGE); //.NET的服务端Soap1.1需要,不加会报错误:服务器未能识别 HTTP 头 SOAPAction 的值
Map<String, Object> requestContext = dispatch.getRequestContext();
requestContext.put(BindingProvider.SOAPACTION_USE_PROPERTY, Boolean.TRUE);
requestContext.put(BindingProvider.SOAPACTION_URI_PROPERTY, "http://webxml.com.cn/toTraditionalChinese"); Source orderSource = dispatch.invoke(xmlSource);
StreamResult result = new StreamResult(new ByteArrayOutputStream());
Transformer trans = TransformerFactory.newInstance().newTransformer();
trans.transform(orderSource, result);
ByteArrayOutputStream baos = (ByteArrayOutputStream) result.getOutputStream();
String responseContent = new String(baos.toByteArray());
System.out.println(responseContent); Reader file = new StringReader(responseContent);
SAXReader reader = new SAXReader();
Document dc = reader.read(file);
//节点名称为toTraditionalChineseResult 命名空间为http://webxml.com.cn/
String r = dc.selectSingleNode("//*[local-name()='toTraditionalChineseResult' and namespace-uri()='http://webxml.com.cn/']").getText().trim();
System.out.println(r);
} catch (Exception e) {
e.printStackTrace();
}
} public static void main(String[] args) {
//Soap1.1对应的portName为TraditionalSimplifiedWebServiceSoap,Soap1.2对应的portName为TraditionalSimplifiedWebServiceSoap12
dispatchPayload("TraditionalSimplifiedWebServiceSoap", "小学");
dispatchPayload("TraditionalSimplifiedWebServiceSoap12", "大学"); //Soap1.1对应的soapNamespace为http://schemas.xmlsoap.org/soap/envelope/,Soap1.1对应的soapNamespace为http://www.w3.org/2003/05/soap-envelope
dispatchMessage("http://schemas.xmlsoap.org/soap/envelope/", "TraditionalSimplifiedWebServiceSoap", "小学");
dispatchMessage("http://www.w3.org/2003/05/soap-envelope", "TraditionalSimplifiedWebServiceSoap12", "大学");
} }

2.2、Proxy方式

该方式代码很简洁,需把接口类ITestService拷贝到客户端工程里。调用本地服务如下:

package com.inspur.ws;

import java.net.URL;

import javax.xml.namespace.QName;
import javax.xml.ws.Service; import com.inspur.zsyw.ws.ITestService; /**
* JAX-WS Proxy调用 ,需把接口类拷贝到客户端
*
*/
public class JaxWsProxy {
private static String url = "http://10.40.103.48:9006/zsywservice/TestService?wsdl";
private static String targetNamespace = "http://ws.zsyw.inspur.com/"; public static void proxy(String param) {
try {
QName qname = new QName(targetNamespace, "TestService");
Service service = Service.create(new URL(url), qname);
ITestService testService = service.getPort(ITestService.class);
System.out.println(testService.hello(param));
} catch (Exception e) {
e.printStackTrace();
}
} public static void main(String[] args) {
proxy("大学");
}
}

2.3、RPC方式

RPC方式已不被推荐使用了,但JAX-WS依然支持。改方式与Proxy有点相似,也需把接口类ITestService拷贝到客户端工程里面;与Proxy方式不同的是:接口类还需继承java.rmi.Remote接口,使用的类是javax.xml.rpc包下

package com.inspur.ws;

import java.net.URL;

import javax.xml.namespace.QName;
import javax.xml.rpc.Service;
import javax.xml.rpc.ServiceFactory; import com.inspur.zsyw.ws.ITestService; /**
* JAX-WS RPC调用 ,需把接口类拷贝到客户端,接口类需继承java.rmi.Remote接口
*
*/
public class JaxWsRpc {
private static String url = "http://10.40.103.48:9006/zsywservice/TestService?wsdl";
private static String targetNamespace = "http://ws.zsyw.inspur.com/"; public static void rpc(String param) {
try {
ServiceFactory serviceFactory = ServiceFactory.newInstance();
Service service = serviceFactory.createService(new URL(url), new QName(targetNamespace, "TestService"));
ITestService testService = (ITestService) service.getPort(ITestService.class);
String result = testService.hello(param);
System.out.println(result);
} catch (Exception e) {
e.printStackTrace();
}
} public static void main(String[] args) {
rpc("大学");
}
}

Java调用WebService方法总结(2)--JAX-WS调用WebService的更多相关文章

  1. JS调用OC方法并传值,OC调用JS方法并传值////////////////////////zz

     iOS开发-基于原生JS与OC方法互相调用并传值(附HTML代码)     最近项目里面有有个商品活动界面,要与web端传值,将用户在网页点击的商品id 传给客户端,也就是js交互,其实再说明白一点 ...

  2. Java调用WebService方法总结(8)--soap.jar调用WebService

    Apache的soap.jar是一种历史很久远的WebService技术,大概是2001年左右的技术,所需soap.jar可以在http://archive.apache.org/dist/ws/so ...

  3. Java中一个方法只被一个线程调用一次

    1.想在运行时抛出异常,终止方法的运行 private final Set<Long> THREADS = new HashSet<>(); public void someM ...

  4. Java调用WebService方法总结(1)--准备工作

    WebService是一种跨编程语言.跨操作系统平台的远程调用技术,已存在很多年了,很多接口也都是通过WebService方式来发布的:本系列文章主要介绍Java调用WebService的各种方法,使 ...

  5. Java 调用对象方法的执行过程

    弄清调用对象方法的执行过程十分重要.下面是调用过程的详细描述: 1) 编译器查看对象的声明类型和方法名.假设调用x.f(param),且隐式参数x声明为C类的对象.需要注意的是:有可能存在多个名为f, ...

  6. java nio使用方法(转)

    最近由于工作关系要做一些Java方面的开发,其中最重要的一块就是Java NIO(New I/O),尽管很早以前了解过一些,但并没有认真去看过它的实现原理,也没有机会在工作中使用,这次也好重新研究一下 ...

  7. 【细说Java】揭开Java的main方法神秘的面纱

    大家都知道,main方法是Java应用程序的入口,其定义格式为: public static void main(String[] args) 可是为什么要这么定义呢?不这样定义可以么?main方法可 ...

  8. 【细说Java】揭开Java的main方法神秘的面纱(转)

    大家都知道,main方法是Java应用程序的入口,其定义格式为: public static void main(String[] args) 可是为什么要这么定义呢?不这样定义可以么?main方法可 ...

  9. Asp.Net Core SignalR 用泛型Hub优雅的调用前端方法及传参

    继续学习 最近一直在使用Asp.Net Core SignalR(下面成SignalR Core)为小程序提供websocket支持,前端时间也发了一个学习笔记,在使用过程中稍微看了下它的源码,不得不 ...

  10. Java多线程-run方法与start方法的区别

    package com.interview; /** * java多线程的两种实现方式以及run.start方法的区别 * @author MEI.LIU * */ public class Thre ...

随机推荐

  1. Redis 下载 安装

    Redis 官网 https://redis.io/ github 主页 https://github.com/antirez/redis 下载页面 https://redis.io/download ...

  2. better-scroll在vue项目中的使用

    1.准备工作 在项目中安装better-scroll: npm install --save better-scroll 组件中引入插件 import BScroll from "bette ...

  3. IDEA文件查找功能失效(ctrl+shift+N)

    由于断电.蓝屏引起的强制关机等情况,会导出IDEA文件查找功能失效,Enter file name窗口输入的文字显示红色,无法查出需要的文件.  解决方法: 可以点击File,选择Invalidate ...

  4. [转]c++多线程编程之pthread线程深入理解

    多线程编程之pthread线程深入理解         Pthread是 POSIX threads 的简称,是POSIX的线程标准.           前几篇博客已经能给你初步的多线程概念.在进一 ...

  5. RSA 签名、验证、加密、解密帮助类

    import java.io.IOException; import java.security.InvalidKeyException; import java.security.KeyFactor ...

  6. 【WebSocket】WebSocket快速入门

    WebSocket介绍 WebSocket 是 HTML5 开始提供的一种在单个 TCP 连接上进行全双工通讯的协议. WebSocket 使得客户端和服务器之间的数据交换变得更加简单,允许服务端主动 ...

  7. App installation failed (A valid provisioning profile for this executable was not found)

    真机调试build success ,App installation failed (A valid provisioning profile for this executable was not ...

  8. matlab学习笔记9 高级绘图命令_2 图形的高级控制_视点控制和图形旋转_色图和颜色映像_光照和着色

    一起来学matlab-matlab学习笔记9 高级绘图命令_2 图形的高级控制_视点控制和图形旋转_色图和颜色映像_光照和着色 觉得有用的话,欢迎一起讨论相互学习~Follow Me 参考书籍 < ...

  9. 使用adb命令控制anroid手机

     adb工具即Android Debug Bridge(安卓调试桥) tools.它就是一个命令行窗口,用于通过电脑端与模拟器或者真实设备交互.在某些特殊的情况下进入不了系统或者需要自动化测试的时候, ...

  10. [LeetCode] 90. Subsets II 子集合 II

    Given a collection of integers that might contain duplicates, nums, return all possible subsets (the ...