用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. Systemback制作大于4G的Ubuntu系统镜像

    1 安装Systemback 依此执行如下命令. sudo apt-get update sudo add-apt-repository ppa:nemh/systemback sudo apt-ge ...

  2. __gcd-最大公约数

    __gcd-最大公约数 最大公约数(greatest common divisor,简写为gcd:或highest common factor,简写为hcf) __gcd(x,y)是algorithm ...

  3. ES 基本用法

    转自:https://www.cnblogs.com/rodge-run/p/7760308.html ES的基本概念 1> 集群和节点 一个es集群是由一个或多和es节点组成的集合 每一个集群 ...

  4. postMan下使用xdebug

    增加 ?XDEBUG_SESSION_START=PHPSTORM 例: {{url}}/manage/getuserinfo?XDEBUG_SESSION_START=PHPSTORM

  5. JAVA微信开发-如何保存包含特殊字符的微信昵称

    我们在做微信开发的时候,有一个很重要的就是通过openid获取用户的详细信息,包含昵称,头像,省,市,区的信息,但是现在移动时代,很多人追求个性,在名字当中大量使用火星文或者表情符.(本人实际测试过一 ...

  6. Flutter UI系统

    我们可以看到,无论是Android SDK还是iOS的UIKit 的职责都是相同的,它们只是语言载体和底层的系统不同而已.那么可不可以实现这么一个UI系统:可以使用同一种编程语言开发,然后针对不同操作 ...

  7. [LeetCode] 518. Coin Change 2 硬币找零 2

    You are given coins of different denominations and a total amount of money. Write a function to comp ...

  8. Redis 主从、哨兵Sentinel、Jedis

    Redis 主从.哨兵Sentinel.Jedis 2017年02月15日 15:52:48 有且仅有 阅读数 6183 文章标签: redis主从sentineljedis 更多 分类专栏: 7/1 ...

  9. 【Python学习之七】类和对象

    环境 虚拟机:VMware 10 Linux版本:CentOS-6.5-x86_64 客户端:Xshell4 FTP:Xftp4 python3.6 一.面向对象编程1.概念(1)面向对象编程(OOP ...

  10. Appium UiWatchers 监听解决各种非期待弹窗,弹层,弹弹弹等问题

    app自动化时,各种不期待的弹层弹窗,升级广告等时有飞出,由于弹窗具有不定时,不定页面等很多不确定性.有的弹窗很不友好,不×掉,很难进行下一步操作,造成 测试用例失败.而判断是否有弹窗,弹层很麻烦.研 ...