Java调用WebService方法总结(2)--JAX-WS调用WebService
用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的更多相关文章
- JS调用OC方法并传值,OC调用JS方法并传值////////////////////////zz
iOS开发-基于原生JS与OC方法互相调用并传值(附HTML代码) 最近项目里面有有个商品活动界面,要与web端传值,将用户在网页点击的商品id 传给客户端,也就是js交互,其实再说明白一点 ...
- Java调用WebService方法总结(8)--soap.jar调用WebService
Apache的soap.jar是一种历史很久远的WebService技术,大概是2001年左右的技术,所需soap.jar可以在http://archive.apache.org/dist/ws/so ...
- Java中一个方法只被一个线程调用一次
1.想在运行时抛出异常,终止方法的运行 private final Set<Long> THREADS = new HashSet<>(); public void someM ...
- Java调用WebService方法总结(1)--准备工作
WebService是一种跨编程语言.跨操作系统平台的远程调用技术,已存在很多年了,很多接口也都是通过WebService方式来发布的:本系列文章主要介绍Java调用WebService的各种方法,使 ...
- Java 调用对象方法的执行过程
弄清调用对象方法的执行过程十分重要.下面是调用过程的详细描述: 1) 编译器查看对象的声明类型和方法名.假设调用x.f(param),且隐式参数x声明为C类的对象.需要注意的是:有可能存在多个名为f, ...
- java nio使用方法(转)
最近由于工作关系要做一些Java方面的开发,其中最重要的一块就是Java NIO(New I/O),尽管很早以前了解过一些,但并没有认真去看过它的实现原理,也没有机会在工作中使用,这次也好重新研究一下 ...
- 【细说Java】揭开Java的main方法神秘的面纱
大家都知道,main方法是Java应用程序的入口,其定义格式为: public static void main(String[] args) 可是为什么要这么定义呢?不这样定义可以么?main方法可 ...
- 【细说Java】揭开Java的main方法神秘的面纱(转)
大家都知道,main方法是Java应用程序的入口,其定义格式为: public static void main(String[] args) 可是为什么要这么定义呢?不这样定义可以么?main方法可 ...
- Asp.Net Core SignalR 用泛型Hub优雅的调用前端方法及传参
继续学习 最近一直在使用Asp.Net Core SignalR(下面成SignalR Core)为小程序提供websocket支持,前端时间也发了一个学习笔记,在使用过程中稍微看了下它的源码,不得不 ...
- Java多线程-run方法与start方法的区别
package com.interview; /** * java多线程的两种实现方式以及run.start方法的区别 * @author MEI.LIU * */ public class Thre ...
随机推荐
- DIV块中 元素垂直居中
1 DIV块中 元素垂直居中 作者:知乎用户链接:https://www.zhihu.com/question/20543196/answer/99429177来源:知乎著作权归作者所有.商业转载请联 ...
- Edusoho之Basic Authentication
通过如下代码,可以正常请求并获取对应的数据: curl -X POST -H "Accept:application/vnd.edusoho.v2+json" -H "A ...
- 第10组 Alpha冲刺(5/6)
链接部分 队名:女生都队 组长博客: 博客链接 作业博客:博客链接 小组内容 恩泽(组长) 过去两天完成了哪些任务 描述 学习调用中国天气网API,接近实现天气推送功能 对天气推送的形式进行讨论及重确 ...
- 第2课第6节_Java面向对象编程_包和权限_P【学习笔记】
摘要:韦东山android视频学习笔记 1.使用package定义编译的时候存放的位置 package a.b.c.d; public class Package { public static v ...
- iostat参数说明
一直不太会用这个参数.现在认真研究了一下iostat,因为刚好有台重要的服务器压力高,所以放上来分析一下.下面这台就是IO有压力过大的服务器 # iostat -x 1 10 Linux 2.6.18 ...
- plsql 使用desc命令提示invalid sql statement
使用SQL WINDOW运行desc命令就报invalid sql statement错误!! 使用Command Window就可以!!!
- Oracle中如何修改已存在数据的列名的数据类型
在oracle中,如何修改已存在数据列名的数据类型 一般人直接在表结构设计这里修改,这里只适合修改列没有数据,可修改 那么,如何这个列是有数据,是怎么修改的呢? 直接修改会Oracle错误 第一步:先 ...
- linux shell中如何批量添加一行内容到某些文件的末尾?
答:先使用find找出要指定的某些文件,然后使用xargs和sed工具将内容插入到这些文件的末尾 find . -name 'filename*' | xargs sed -i '$a\added-c ...
- Java12新特性 -- 只保留一个 AArch64 实现
现状 当前 Java 11 及之前版本JDK中存在两个64位ARM端口.这些文件的主要来源位于src/hotspot/cpu/arm 和 open/src/hotspot/cpu/aarch64 目录 ...
- Quartus ii 设计中的差分信号在例化时的命名规则
在Quartus中做设计,如果使用了差分信号的,如DDR的IP中的mem_ck与mem_ck_n,mem_dqs与mem_dqs_n,将其引入输出端口时,对其命名有一定的规则,否则就会出现错误. 如下 ...