Java開發(fā)或調(diào)用WebService的幾種方式總結(jié)
一.JDK自帶的 JAX-WS 方式開發(fā)WebService服務(wù)
1.服務(wù)端開發(fā)與發(fā)布
- 編寫接口
@WebService public interface JaxWsDemo { String helloJaxWS(String userName); }
- 編寫接口的實(shí)現(xiàn)類
@WebService public class JaxWsDemoImpl implements JaxWsDemo { @WebMethod @WebResult(name = "jaxWSResult") @Override public String helloJaxWS(@WebParam(name = "userName")String userName) { return "hello," + userName + "This is a Web Service developed through JAX-WS"; } }
- 發(fā)布服務(wù)
public class JAXWSPublishMain { public static void main(String[] args) { String address = "http://127.0.0.1:8888/JaxWSTest"; Endpoint.publish(address, new JaxWsDemoImpl()); System.out.println("WebService 服務(wù)已發(fā)布!"); } }
- 訪問已發(fā)布的WebService服務(wù)
打開瀏覽器輸入http://127.0.0.1:8888/JaxWSTest?wsdl訪問,如下面內(nèi)容
截圖內(nèi)容1
<!-- Published by JAX-WS RI (http://jax-ws.java.net). RI's version is JAX-WS RI 2.2.9-b130926.1035 svn-revision#5f6196f2b90e9460065a4c2f4e30e065b245e51e. --> <!-- Generated by JAX-WS RI (http://jax-ws.java.net). RI's version is JAX-WS RI 2.2.9-b130926.1035 svn-revision#5f6196f2b90e9460065a4c2f4e30e065b245e51e. --> <definitions xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" xmlns:wsp="http://www.w3.org/ns/ws-policy" xmlns:wsp1_2="http://schemas.xmlsoap.org/ws/2004/09/policy" xmlns:wsam="http://www.w3.org/2007/05/addressing/metadata" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:tns="http://wsimpl.jaxws/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://schemas.xmlsoap.org/wsdl/" targetNamespace="http://wsimpl.jaxws/" name="JaxWsDemoImplService"> <types> <xsd:schema> <xsd:import namespace="http://wsimpl.jaxws/" schemaLocation="http://127.0.0.1:8888/JaxWSTest?xsd=1"/> </xsd:schema> </types> <message name="helloJaxWS"> <part name="parameters" element="tns:helloJaxWS"/> </message> <message name="helloJaxWSResponse"> <part name="parameters" element="tns:helloJaxWSResponse"/> </message> <portType name="JaxWsDemoImpl"> <operation name="helloJaxWS"> <input wsam:Action="http://wsimpl.jaxws/JaxWsDemoImpl/helloJaxWSRequest" message="tns:helloJaxWS"/> <output wsam:Action="http://wsimpl.jaxws/JaxWsDemoImpl/helloJaxWSResponse" message="tns:helloJaxWSResponse"/> </operation> </portType> <binding name="JaxWsDemoImplPortBinding" type="tns:JaxWsDemoImpl"> <soap:binding transport="http://schemas.xmlsoap.org/soap/http" style="document"/> <operation name="helloJaxWS"> <soap:operation soapAction=""/> <input> <soap:body use="literal"/> </input> <output> <soap:body use="literal"/> </output> </operation> </binding> <service name="JaxWsDemoImplService"> <port name="JaxWsDemoImplPort" binding="tns:JaxWsDemoImplPortBinding"> <soap:address location="http://127.0.0.1:8888/JaxWSTest"/> </port> </service> </definitions>
瀏覽器中輸入wsdl文檔中的 http://127.0.0.1:8888/JaxWSTest?xsd=1可查看綁定的參數(shù)等信息看如下圖:
截圖內(nèi)容2
<!-- Published by JAX-WS RI (http://jax-ws.java.net). RI's version is JAX-WS RI 2.2.9-b130926.1035 svn-revision#5f6196f2b90e9460065a4c2f4e30e065b245e51e. --> <xs:schema xmlns:tns="http://wsimpl.jaxws/" xmlns:xs="http://www.w3.org/2001/XMLSchema" version="1.0" targetNamespace="http://wsimpl.jaxws/"> <xs:element name="helloJaxWS" type="tns:helloJaxWS"/> <xs:element name="helloJaxWSResponse" type="tns:helloJaxWSResponse"/> <xs:complexType name="helloJaxWS"> <xs:sequence> <xs:element name="userName" type="xs:string" minOccurs="0"/> </xs:sequence> </xs:complexType> <xs:complexType name="helloJaxWSResponse"> <xs:sequence> <xs:element name="jaxWSResult" type="xs:string" minOccurs="0"/> </xs:sequence> </xs:complexType> </xs:schema>
- jdk自帶生成WebService的wsimport命令
-encoding : 指定編碼格式
-keep:是否生成java源文件
-d:指定.class文件的輸出目錄
-s:指定.java文件的輸出目錄, 此目錄必須存在
-p:定義生成類的包名,不定義的話有默認(rèn)包名
-verbose:在控制臺(tái)顯示輸出信息
-b:指定jaxws/jaxb綁定文件或額外的schemas
-extension:使用擴(kuò)展來(lái)支持SOAP1.2
# 舉例
wsimport -encoding utf-8 -keep -d D:\temp -p com.lawyer.user -verbose http://IP:port/serverName?wsdl
2.客戶端開發(fā)與測(cè)試
- 生成客戶端源碼
切換到要生成客戶端源碼的路徑下,如下:
cd F:\SpringBootProjects\webServiceDemo\jwsDemo\src\main\java\demoOne\client>
根據(jù)wsdl文檔地址生成源碼信息:
F:\SpringBootProjects\webServiceDemo\jwsDemo\src\main\java\demoOne\client> wsimport -d F:\SpringBootProjects\webServiceDemo\jwsDemo\src\main\java\demoOne\client -keep -verbose http://127.0.0.1:8888/JaxWSTest?wsdl
參數(shù)說(shuō)明:
wsimport : 導(dǎo)入命令,如果使用cxf就換成 wsdl2java 命令
- -d [源碼位置] : 指定要生成的源碼的目錄,不指定則默認(rèn)在哪個(gè)目錄打開的cmd窗口,就生在那個(gè)目錄下
- -keep : 是否生成*.java的源文件,寫了此參數(shù)則直接生成*.java與*.class文件,不寫此參數(shù)則只有*.class文件
- -verbose : 顯示文件生成過(guò)程中的詳細(xì)信息
- -p [包名]: 指定要生成在哪個(gè)包下,不指定生成時(shí)取默認(rèn)
- 客戶端代碼生成后測(cè)試
package demoOne.client; import demoone.JaxWsDemoImplService; /** * Created by IntelliJ IDEA. * User: jinshengyuan * Date: 2019-03-13 * Time: 10:34 * description: 客戶端測(cè)試 **/ public class ClientTest { public static void main(String[] args) { demoone.JaxWsDemoImplService implService = new JaxWsDemoImplService(); demoone.JaxWsDemoImpl jaxWsDemo = (demoone.JaxWsDemoImpl)implService.getJaxWsDemoImplPort(); String aa = jaxWsDemo.helloJaxWS("Tom "); System.out.println("調(diào)用WebService執(zhí)行結(jié)果:"+aa); } }
執(zhí)行結(jié)果:
調(diào)用WebService執(zhí)行結(jié)果:hello,Tom This is a Web Service developed through JAX-WS
二.Axis1.4調(diào)用.Net返回值為DataSet類型的WebService接口
1.相關(guān)說(shuō)明
- JDK版本:1.8.0_172
- axis版本:Axis1.4
2. Axis1.4客戶端WebService服務(wù)
1.Axis1.4下載
- 官網(wǎng):http://axis.apache.org/axis/
- 下載后是一個(gè)壓縮文件:axis-bin_1.4.zip
- 非maven環(huán)境,則導(dǎo)入axis-bin_1.4.zip包下的lib目錄下的所有jar包,如下圖:
4.maven環(huán)境的話,在pom.xml中添加下面的依賴即可
<!--Axis1.4 及其依賴 begin--> <!-- https://mvnrepository.com/artifact/org.apache.axis/axis --> <dependency> <groupId>org.apache.axis</groupId> <artifactId>axis</artifactId> <version>1.4</version> </dependency> <!-- https://mvnrepository.com/artifact/jaxrpc/jaxrpc --> <!-- https://mvnrepository.com/artifact/axis/axis-jaxrpc --> <dependency> <groupId>axis</groupId> <artifactId>axis-jaxrpc</artifactId> <version>1.4</version> </dependency> <!-- https://mvnrepository.com/artifact/axis/axis-ant --> <dependency> <groupId>axis</groupId> <artifactId>axis-ant</artifactId> <version>1.4</version> </dependency> <!-- https://mvnrepository.com/artifact/axis/axis-saaj --> <dependency> <groupId>axis</groupId> <artifactId>axis-saaj</artifactId> <version>1.4</version> </dependency> <!-- https://mvnrepository.com/artifact/wsdl4j/wsdl4j --> <dependency> <groupId>wsdl4j</groupId> <artifactId>wsdl4j</artifactId> <version>1.6.3</version> </dependency> <!-- https://mvnrepository.com/artifact/commons-discovery/commons-discovery --> <dependency> <groupId>commons-discovery</groupId> <artifactId>commons-discovery</artifactId> <version>0.5</version> </dependency> <!--Axis1.4 及其依賴 end--> <!-- 引入dom4j 解析數(shù)據(jù)時(shí)用--> <!-- https://mvnrepository.com/artifact/org.dom4j/dom4j --> <dependency> <groupId>org.dom4j</groupId> <artifactId>dom4j</artifactId> <version>2.1.1</version> </dependency>
2.WebService服務(wù)接口地址及方法
- 地址:http://www.webxml.com.cn/WebServices/WeatherWebService.asmx
- 調(diào)用的方法:http://www.webxml.com.cn/WebServices/WeatherWebService.asmx/getSupportDataSet
3.編寫調(diào)用WebService服務(wù)的方法及數(shù)據(jù)解析
- 編寫調(diào)用WebService服務(wù)的客戶端java類,并打印結(jié)果,類名為:Axis1_Client
package com.yuan; import org.apache.axis.client.Call; import org.apache.axis.client.Service; import org.apache.axis.encoding.XMLType; import org.apache.axis.message.MessageElement; import org.apache.axis.types.Schema; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.DocumentHelper; import org.dom4j.Element; import org.junit.Test; import javax.xml.namespace.QName; import java.net.URL; import java.util.Iterator; import java.util.List; /** * Created by IntelliJ IDEA. * User: jinshengyuan * Date: 2019-01-15 * Time: 15:13 * description: **/ public class Axis1_Client { /** * 使用dom4j解析數(shù)據(jù) */ @Test public void axisWSInvoke(){ String dataSetDataStr = axisInvokeNetDataSetData(); //System.out.println(dataSetDataStr); if(dataSetDataStr != null){ try { Document doc = DocumentHelper.parseText(dataSetDataStr);// 將字符串轉(zhuǎn)為XML Element root = doc.getRootElement();// 獲取根節(jié)點(diǎn) Iterator iterator = root.elementIterator("Zone");//迭代節(jié)點(diǎn) String id,zone; while(iterator.hasNext()){ Element element = (Element) iterator.next(); id = element.elementTextTrim("ID");//取出Zone節(jié)點(diǎn)下的ID元素的值 zone = element.elementTextTrim("Zone");//取出Zone節(jié)點(diǎn)下的Zone元素的值 System.out.println("Id:"+id+"=============================Zone:"+zone); } } catch (DocumentException e) { e.printStackTrace(); } } } /** * 調(diào)用.Net寫的返回值為DataSet類型的WebService服務(wù) * @return */ public String axisInvokeNetDataSetData(){ Service service = new Service(); String strXml = null; Call call = null; try { call = (Call) service.createCall(); call.setTargetEndpointAddress(new URL("http://www.webxml.com.cn/WebServices/WeatherWebService.asmx"));//WSURL,注意不要帶?wsdl //調(diào)用方法方法前設(shè)置相關(guān)參數(shù) call.setOperationName(new QName("http://WebXml.com.cn/", "getSupportDataSet")); call.setReturnType(XMLType.XSD_SCHEMA);//返回類型,這里一定要傳入 XMLType.XSD_SCHEMA 類型 call.setUseSOAPAction(true); call.setSOAPActionURI("http://WebXml.com.cn/getSupportDataSet");//soapAction Object obj = call.invoke((Object[]) null); Schema schema = (Schema) obj; MessageElement[] messageElements = schema.get_any(); List messageHead = messageElements[0].getChildren();//消息頭,DataSet對(duì)象 List messageBody = messageElements[1].getChildren();//消息體信息,DataSet對(duì)象,最終需要解析的數(shù)據(jù) if (messageBody.size() > 0) { String head = messageHead.get(0).toString();//消息頭,DataSet對(duì)象 String diffgr = messageBody.get(0).toString();//消息體的字符串形式 strXml = diffgr; System.out.println("head:\n"+head); System.out.println("diffgr:\n" + diffgr); } } catch (Exception e) { e.printStackTrace(); } return strXml; } }
- 輸出結(jié)果:
Id:1=============================Zone:直轄市
Id:2=============================Zone:特別行政區(qū)
Id:3=============================Zone:黑龍江
Id:4=============================Zone:吉林
Id:5=============================Zone:遼寧
Id:6=============================Zone:內(nèi)蒙古
Id:7=============================Zone:河北
Id:8=============================Zone:河南
Id:9=============================Zone:山東
Id:10=============================Zone:山西
Id:11=============================Zone:江蘇
Id:12=============================Zone:安徽
Id:13=============================Zone:陜西
Id:14=============================Zone:寧夏
Id:15=============================Zone:甘肅
Id:16=============================Zone:青海
Id:17=============================Zone:湖北
Id:18=============================Zone:湖南
Id:19=============================Zone:浙江
Id:20=============================Zone:江西
Id:21=============================Zone:福建
Id:22=============================Zone:貴州
Id:23=============================Zone:四川
Id:24=============================Zone:廣東
Id:25=============================Zone:廣西
Id:26=============================Zone:云南
Id:27=============================Zone:海南
Id:28=============================Zone:新疆
Id:29=============================Zone:西藏
Id:30=============================Zone:臺(tái)灣
Id:31=============================Zone:亞洲
Id:32=============================Zone:歐洲
Id:33=============================Zone:非洲
Id:34=============================Zone:北美洲
Id:35=============================Zone:南美洲
Id:36=============================Zone:大洋洲
三. CXF 開發(fā)WebService接口
1. jax-ws實(shí)現(xiàn)
場(chǎng)景:CXF結(jié)合Spring實(shí)現(xiàn)發(fā)布與調(diào)用簡(jiǎn)單的WebService
- 導(dǎo)入包
- pom.xml引入cxf的依賴即可
- 開發(fā)java接口與實(shí)現(xiàn)類代碼
- 編寫接口
package com.ssm.webservice; import javax.jws.WebMethod; import javax.jws.WebParam; import javax.jws.WebResult; import javax.jws.WebService; /** * Created by IntelliJ IDEA. * User: jinshengyuan * Date: 2018-11-09 * Time: 9:04 * description: **/ @WebService public interface Hello { @WebMethod @WebResult(name = "result") String sayHello(@WebParam(name = "name") String name); }
- 編寫接口的實(shí)現(xiàn)類
package com.ssm.webservice.impl; import com.ssm.dao.sysManagement.ComLogMapper; import com.ssm.model.ComLog; import com.ssm.service.sysManagement.ComLogService; import com.ssm.utils.CommonsUtil; import com.ssm.webservice.Hello; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.text.SimpleDateFormat; import java.util.Date; /** * Created by IntelliJ IDEA. * User: jinshengyuan * Date: 2018-11-09 * Time: 9:06 * description: **/ public class HelloImpl implements Hello { //這里跟controller中調(diào)用Service一樣,使用@Autowired注解自動(dòng)注入service @Autowired ComLogService comLogService; @Override public String sayHello(String name) { //從數(shù)據(jù)庫(kù)中獲取當(dāng)前系統(tǒng)日期 Date date = comLogService.getCurrentDatetime(); String currentDateTime = null; if(date != null){ SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); currentDateTime = dateFormat.format(date); System.out.println("系統(tǒng)日期:"+currentDateTime); } return "hello," + name + ",當(dāng)前時(shí)間為:"+currentDateTime; } }
- 與spring集成
- spring.xml文件中的核心配置
<!-- 引入CXF配置文件,低版本(3.0以下)還需引入其他兩個(gè)文件 --> <import resource="classpath:META-INF/cxf/cxf.xml" /> <!-- 配置方式1 注意:serviceClass為接口類并非接口的實(shí)現(xiàn)類 --> <jaxws:server serviceClass="com.ssm.webservice.Hello" address="/webServiceTestA"></jaxws:server> <!--訪問地址:http://localhost:8080/ssm/webService/webServiceTestA?wsdl--> <!-- 配置方式2 注意:implementor為接口的具體實(shí)現(xiàn)類,與springmvc整合時(shí),推薦使用這種方式,如果使用配置方式1,則會(huì)在訪問時(shí),提示如下錯(cuò)誤: org.apache.cxf.interceptor.Fault: Could not instantiate service class com.ssm.webservice.Hello because it is an interface. --> <jaxws:endpoint implementor="com.ssm.webservice.impl.HelloImpl" address="/webServiceTest"></jaxws:endpoint> <!--訪問地址:http://localhost:8080/ssm/webService/webServiceTest?wsdl-->
- web.xml中的配置
<!-- cxf服務(wù)啟動(dòng)servlet --> <servlet> <servlet-name>CXFServlet</servlet-name> <servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>CXFServlet</servlet-name> <!--工程名(ssm)后面緊跟的 url--> <url-pattern>/webService/*</url-pattern> </servlet-mapping>
- 測(cè)試
- 打開瀏覽器,輸入http://localhost:8080/ssm/webService/webServiceTest?wsdl進(jìn)行測(cè)試
2. CXF-RESTFul服務(wù)實(shí)現(xiàn)
- JAX-RS概述
JAX-RS是Java提供用于開發(fā)RESTful Web服務(wù)基于注解(annotation)的API。JAX-RS旨在定義一個(gè)統(tǒng)一的規(guī)范,使得Java程序員可以使用一套固定的接口來(lái)開發(fā)REST應(yīng)用,避免了依賴第三方框架。同時(shí)JAX-RS使用POJO編程模型和基于注解的配置并集成JAXB,可以有效縮短REST應(yīng)用的開發(fā)周期。JAX-RS只定義RESTful API,具體實(shí)現(xiàn)由第三方提供,如Jersey、Apache CXF等。
JAX-RS包含近五十多個(gè)接口、注解和抽象類:
- javax.ws.rs包含用于創(chuàng)建RESTful服務(wù)資源的高層次(High-level)接 口和注解。
- javax.ws.rs.core包含用于創(chuàng)建RESTful服務(wù)資源的低層次(Low-level)接口和注解。
- javax.ws.rs.ext包含用于擴(kuò)展JAX-RS API支持類型的APIs。
JAX-RS常用注解:
- @Path:標(biāo)注資源類或方法的相對(duì)路徑。
- @GET、@PUT、@POST、@DELETE:標(biāo)注方法的HTTP請(qǐng)求類型。
- @Produces:標(biāo)注返回的MIME媒體類型。
- @Consumes:標(biāo)注可接受請(qǐng)求的MIME媒體類型。
- @PathParam、@QueryParam、@HeaderParam、@CookieParam、@MatrixParam、@FormParam:標(biāo)注方法的參數(shù)來(lái)自于HTTP請(qǐng)求的位置。@PathParam來(lái)自于URL的路徑,@QueryParam來(lái)自于URL的查詢參數(shù),@HeaderParam來(lái)自于HTTP請(qǐng)求的頭信息,@CookieParam來(lái)自于HTTP請(qǐng)求的Cookie。
總結(jié)
到此這篇關(guān)于Java開發(fā)或調(diào)用WebService的幾種方式總結(jié)的文章就介紹到這了,更多相關(guān)Java開發(fā)調(diào)用WebService方式內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Java實(shí)現(xiàn)List去重的五種方法詳解
這篇文章主要為大家詳細(xì)介紹了Java中List去重的5種方法,文中的示例代碼講解詳細(xì),具有一定的學(xué)習(xí)和參考價(jià)值,需要的小伙伴可以了解一下2022-10-10SpringBoot+Redis實(shí)現(xiàn)查找附近用戶的示例代碼
SpringDataRedis提供了十分簡(jiǎn)單的地理位置定位的功能,本文主要介紹了SpringBoot+Redis實(shí)現(xiàn)查找附近用戶的示例代碼,具有一定的參考價(jià)值,感興趣的可以了解一下2024-02-02mybatisplus中的xml對(duì)象參數(shù)傳遞問題
這篇文章主要介紹了mybatisplus中的xml對(duì)象參數(shù)傳遞問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-11-11郵件的組織結(jié)構(gòu)介紹 郵件實(shí)現(xiàn)詳解(三)
這篇文章主要為大家詳細(xì)介紹了郵件的組織結(jié)構(gòu),郵件內(nèi)容的基本格式和具體細(xì)節(jié),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-10-10基于java語(yǔ)言實(shí)現(xiàn)快遞系統(tǒng)
這篇文章主要為大家詳細(xì)介紹了基于java語(yǔ)言實(shí)現(xiàn)快遞系統(tǒng),文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-03-03springcloud-feign調(diào)用報(bào)錯(cuò)問題
這篇文章主要介紹了springcloud-feign調(diào)用報(bào)錯(cuò)問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-08-08Jackson處理Optional時(shí)遇到問題的解決與分析
Optional是Java實(shí)現(xiàn)函數(shù)式編程的強(qiáng)勁一步,并且?guī)椭诜妒街袑?shí)現(xiàn),但是Optional的意義顯然不止于此,下面這篇文章主要給大家介紹了關(guān)于Jackson處理Optional時(shí)遇到問題的解決與分析的相關(guān)資料,需要的朋友可以參考下2022-02-02