赞
踩
仓库地址(gitee) https://gitee.com/GardenerHan/webService
WebService是一种跨编程语言和跨操作系统平台的远程调用技术。
SOAP
Web service建好以后,你或者其他人就会去调用它。简单对象访问协议(SOAP)提供了标准的RPC方法来调用Web service。实际上,SOAP在这里有点用词不当:它意味着下面的Web service是以对象的方式表示的,但事实并不一定如此:你完全可以把你的Web service写成一系列的C函数,并仍然使用SOAP进行调用。SOAP规范定义了SOAP消息的格式,以及怎样通过HTTP协议来使用SOAP。SOAP也是基于XML(标准通用标记语言下的一个子集)和XSD的,XML是SOAP的数据编码方式。
WSDL
你会怎样向别人介绍你的Web service有什么功能,以及每个函数调用时的参数呢?你可能会自己写一套文档,你甚至可能会口头上告诉需要使用你的Web service的人。这些非正式的方法至少都有一个严重的问题:当程序员坐到电脑前,想要使用你的Web service的时候,他们的工具(如Visual Studio)无法给他们提供任何帮助,因为这些工具根本就不了解你的Web service。
解决方法是:用机器能阅读的方式提供一个正式的描述文档。Web service描述语言(WSDL)就是这样一个基于XML(标准通用标记语言下的一个子集)的语言,用于描述Web service及其函数、参数和返回值。WSDL既是机器可阅读的,又是人可阅读的,这将是一个很大的好处。一些最新的开发工具既能根据你的Web service生成WSDL文档,又能导入WSDL文档,生成调用相应Web service的代码。
UDDI
Universal Description, Discovery and Integration
为加速Web Service的推广、加强Web Service的互操作能力而推出的一个计划,基于标准的服务描述和发现的规范(specification)。
以资源共享的方式由多个运作者一起以Web Service的形式运作UDDI商业注册中心。
UDDI计划的核心组件是UDDI商业注册,它使用XML文档来描述企业及其提供的Web Service。
UDDI商业注册提供三种信息:
White Page包含地址、联系方法、已知的企业标识。
Yellow Page包含基于标准分类法的行业类别。
Green Page包含关于该企业所提供的Web Service的技术信息,其形式可能是指向文件或URL的指针,而这些文件或URL是为服务发现机制服务的。
<dependencies>
<!-- https://mvnrepository.com/artifact/org.apache.cxf/cxf-rt-frontend-jaxws -->
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-frontend-jaxws</artifactId>
<version>3.2.7</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.cxf/cxf-rt-transports-http-jetty -->
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-transports-http-jetty</artifactId>
<version>3.2.7</version>
</dependency>
</dependencies>
import javax.jws.WebService;
@WebService
public interface Demo {
String sayHello(String name, int age);
}
public class DemoService implements Demo {
@Override
public String sayHello(String name, int age) {
return "Hello!!!" + name + "(" + age + " years old)";
}
}
import org.apache.cxf.endpoint.Server;
import org.apache.cxf.jaxws.JaxWsServerFactoryBean;
public class MainService {
public static void main(String[] args) {
JaxWsServerFactoryBean jaxWsServerFactoryBean = new JaxWsServerFactoryBean();
jaxWsServerFactoryBean.setAddress("http://localhost:8080/demo");
jaxWsServerFactoryBean.setServiceClass(DemoService.class);
Server server = jaxWsServerFactoryBean.create();
server.start();
System.out.println("demo服务启动 。。。。");
}
}
import com.hgx.web.service.demo.Demo;
import org.apache.cxf.jaxws.JaxWsProxyFactoryBean;
public class MainClient {
public static void main(String[] args) {
JaxWsProxyFactoryBean jaxWsProxyFactoryBean = new JaxWsProxyFactoryBean();
jaxWsProxyFactoryBean.setAddress("http://localhost:8080/demo");
jaxWsProxyFactoryBean.setServiceClass(Demo.class);
Demo demo = (Demo) jaxWsProxyFactoryBean.create();
System.out.println(demo.sayHello("hgx", 24));
}
}
一条 SOAP 消息就是一个普通的 XML 文档,包含下列元素:
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<soap:Fault>
<faultcode>soap:Server</faultcode>
<faultstring>
No binding operation info while invoking unknown method with params unknown.
</faultstring>
</soap:Fault>
</soap:Body>
</soap:Envelope>
<soapenv:Envelope
xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:q0="http://test.cxf.hgx.com/"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<soapenv:Body>
<q0:sayhello>
<arg0>Jack</arg0>
<arg1>16</arg1>
</q0:sayhello>
</soapenv:Body>
</soapenv:Envelope>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<ns2:sayhelloResponse xmlns:ns2="http://test.cxf.hgx.com/">
<return>Hello, Jack(16 years old)</return>
</ns2:sayhelloResponse>
</soap:Body>
</soap:Envelope>
<definitions> <types> 定义 web service 使用的数据类型 </types> <message> 每个消息均由一个或多个部件组成。可以把它当做java中一个函数调用的参数。 </message> <portType> 它类似Java中的一个函数库(或一个模块、或一个类) </portType> <binding> 为每个端口定义消息格式和协议细节。 </binding> </definitions>
<wsdl:definitions
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/"
xmlns:tns="http://service.hgx.com/"
xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
xmlns:ns1="http://schemas.xmlsoap.org/soap/http"
name="HelloWorldImplService"
targetNamespace="http://service.hgx.com/">
</wsdl:definitions>
标签 | 描述 |
---|---|
name | 我们java程序中服务接口的实现类,SEI定义是:服务接口类+Service后缀,Service自动追加 |
targetNamespace | 命名空间: 相当于Java里面的package它刚好是和我们Java定义中的包名相反 |
其它 | 不变化,不关心 |
xmlns:tns | 相当于Java里面的import, 包名反转 |
wsdl2java
根据wsdl生成文件D:\devEnv\apache-cxf-3.2.7\apache-cxf-3.2.7\bin>wsdl2java http://localhost:8080/demo?wsdl
import com.hgx.web.service.demo.Demo;
import org.apache.cxf.jaxws.JaxWsProxyFactoryBean;
public class WSDLMain {
public static void main(String[] args) {
JaxWsProxyFactoryBean jaxWsProxyFactoryBean = new JaxWsProxyFactoryBean();
jaxWsProxyFactoryBean.setAddress("http://localhost:8080/demo");
jaxWsProxyFactoryBean.setServiceClass(Demo.class);
Demo demo = (Demo) jaxWsProxyFactoryBean.create();
System.out.println(demo.sayHello("hgx", 24));
}
}
D:\devEnv\apache-cxf-3.2.7\apache-cxf-3.2.7\bin>wsdl2java -client http://localhost:8080/demo?wsdl
import java.io.File; import java.net.MalformedURLException; import java.net.URL; import javax.xml.namespace.QName; /** * This class was generated by Apache CXF 3.2.7 * 2019-01-10T18:26:18.045+08:00 * Generated source version: 3.2.7 * */ public final class Demo_DemoServicePort_Client { private static final QName SERVICE_NAME = new QName("http://demo.service.web.hgx.com/", "DemoServiceService"); private Demo_DemoServicePort_Client() { } public static void main(String args[]) throws Exception { URL wsdlURL = DemoServiceService.WSDL_LOCATION; if (args.length > 0 && args[0] != null && !"".equals(args[0])) { File wsdlFile = new File(args[0]); try { if (wsdlFile.exists()) { wsdlURL = wsdlFile.toURI().toURL(); } else { wsdlURL = new URL(args[0]); } } catch (MalformedURLException e) { e.printStackTrace(); } } DemoServiceService ss = new DemoServiceService(wsdlURL, SERVICE_NAME); Demo port = ss.getDemoServicePort(); { System.out.println("Invoking sayHello..."); String _sayHello_arg0 = ""; int _sayHello_arg1 = 0; String _sayHello__return = port.sayHello(_sayHello_arg0, _sayHello_arg1); System.out.println("sayHello.result=" + _sayHello__return); } System.exit(0); } }
1.获得wsdl
http://www.webxml.com.cn/zh_cn/index.aspx
天气:http://ws.webxml.com.cn/WebServices/WeatherWS.asmx
2.根据wsdl生成接口
D:\devEnv\apache-cxf-3.2.7\apache-cxf-3.2.7\bin>wsdl2java http://ws.webxml.com.cn/WebServices/WeatherWS.asmx?wsdl
WSDLToJava Error: http://ws.webxml.com.cn/WebServices/WeatherWS.asmx?wsdl [15,19]: undefined element declaration 's:schema'
http://ws.webxml.com.cn/WebServices/WeatherWS.asmx?wsdl [61,19]: undefined element declaration 's:schema'
http://ws.webxml.com.cn/WebServices/WeatherWS.asmx?wsdl [101,13]: undefined element declaration 's:schema'
e:\weather.wsdl
,先编辑一下,去掉报错的<s:element ref="s:schema" />
wsdl2java e:\weather.wsdl
3.将生成的类包,拷贝到项目下
<dependencies>
<!-- https://mvnrepository.com/artifact/org.apache.cxf/cxf-rt-frontend-jaxws -->
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-frontend-jaxws</artifactId>
<version>3.2.7</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.cxf/cxf-rt-transports-http-jetty -->
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-transports-http-jetty</artifactId>
<version>3.2.7</version>
</dependency>
</dependencies>
import cn.com.webxml.ArrayOfString; import cn.com.webxml.WeatherWS; import cn.com.webxml.WeatherWSSoap; import java.util.List; public class WeatherClient { public static void main(String[] args) { WeatherWSSoap weatherWSSoap = new WeatherWS().getWeatherWSSoap(); //获取国家 ArrayOfString arrayOfString = weatherWSSoap.getRegionCountry(); List<String> list = arrayOfString.getString(); for (String result : list) { System.out.println(result); } //获取省份 ArrayOfString arrayOfString1 = weatherWSSoap.getRegionProvince() ; List<String> list1 = arrayOfString1.getString(); for (String s: list1) { System.out.println(s); } //获取城市 ArrayOfString arrayOfString2 = weatherWSSoap.getSupportCityString("311104") ; List<String> list2 = arrayOfString2.getString(); for (String s: list2) { System.out.println(s); } //获取天气需要账号 ArrayOfString arrayOfString3 = weatherWSSoap.getWeather("1605","123123123") ; List<String> list3 = arrayOfString3.getString(); for (String s: list3) { System.out.println(s); } }
包括:
<dependencies> <!-- https://mvnrepository.com/artifact/org.apache.cxf/cxf-rt-frontend-jaxws --> <dependency> <groupId>org.apache.cxf</groupId> <artifactId>cxf-rt-frontend-jaxws</artifactId> <version>3.2.7</version> </dependency> <!-- https://mvnrepository.com/artifact/org.apache.cxf/cxf-rt-transports-http --> <dependency> <groupId>org.apache.cxf</groupId> <artifactId>cxf-rt-transports-http</artifactId> <version>3.2.7</version> </dependency> <!-- https://mvnrepository.com/artifact/org.apache.cxf/cxf-rt-frontend-jaxrs --> <dependency> <groupId>org.apache.cxf</groupId> <artifactId>cxf-rt-frontend-jaxrs</artifactId> <version>3.2.7</version> </dependency> <!-- https://mvnrepository.com/artifact/org.apache.cxf/cxf-rt-transports-http-jetty --> <dependency> <groupId>org.apache.cxf</groupId> <artifactId>cxf-rt-transports-http-jetty</artifactId> <version>3.2.7</version> </dependency> <!--没有这两个依赖会:No message body writer has been found for class com.hgx.web.service.restful.bean.Student, ContentType: application/json--> <!-- https://mvnrepository.com/artifact/org.apache.cxf/cxf-rt-rs-extension-providers --> <dependency> <groupId>org.apache.cxf</groupId> <artifactId>cxf-rt-rs-extension-providers</artifactId> <version>3.2.7</version> </dependency> <!-- https://mvnrepository.com/artifact/org.codehaus.jettison/jettison --> <dependency> <groupId>org.codehaus.jettison</groupId> <artifactId>jettison</artifactId> <version>1.4.0</version> </dependency> <!--http客服端依赖 --> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.2</version> </dependency> </dependencies>
import javax.ws.rs.FormParam; import javax.xml.bind.annotation.XmlRootElement; import java.util.Date; @XmlRootElement public class Student { @FormParam("number") private Integer number; @FormParam("name") private String name; @FormParam("age") private Integer age; @FormParam("birth") private Date birth; public Student() { } public Student(Integer number, String name, Integer age, Date birth) { this.number = number; this.name = name; this.age = age; this.birth = birth; } public Integer getNumber() { return number; } public void setNumber(Integer number) { this.number = number; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public Date getBirth() { return birth; } public void setBirth(Date birth) { this.birth = birth; } @Override public String toString() { return "Student{" + "number=" + number + ", name='" + name + '\'' + ", age=" + age + ", birth=" + birth + '}'; } }
import javax.ws.rs.*; import javax.ws.rs.core.MediaType; import java.sql.Date; import java.time.Instant; @Path("/rest") public class StudentServer { @Path("/student/{id}") @GET // @Produces("application/json") @Produces(MediaType.APPLICATION_JSON) public Student getStudentById(@PathParam("id") String id) { return new Student(6666, "韩哈哈哈", 20, Date.from(Instant.now())); } }
import com.hgx.web.service.restful.server.StudentServer;
import org.apache.cxf.jaxrs.JAXRSServerFactoryBean;
public class StudentServerMain {
public static void main(String[] args) {
JAXRSServerFactoryBean jAXRSServerFactoryBean = new JAXRSServerFactoryBean();
jAXRSServerFactoryBean.setAddress("http://localhost:8080/studentServce");
jAXRSServerFactoryBean.setResourceClasses(StudentServer.class);
jAXRSServerFactoryBean.create().start();
System.out.println("student server 启动");
}
}
使用 HttpClient需要以下6个步骤:
import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.util.EntityUtils; import java.io.IOException; public class RestClientMain { public static void main(String[] args) throws IOException { // 1. 创建 HttpClient 的实例 CloseableHttpClient httpClient = HttpClientBuilder.create().build(); // 2. 创建某种连接方法的实例 HttpGet httpGet = new HttpGet("http://localhost:8080/studentServce/rest/student/0101"); // 3. 调用第一步中创建好的实例的execute方法来执行第二步中创建好的链接类实例 HttpResponse httpResponse = httpClient.execute(httpGet); // 4. 读response获取HttpEntity if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { HttpEntity entity = httpResponse.getEntity(); // 5. 对得到后的内容进行处理 String result = EntityUtils.toString(entity, "utf-8"); System.out.println(result); EntityUtils.consume(entity); } else { System.err.println(httpResponse.getStatusLine()); } // 6. 释放连接。无论执行方法是否成功,都必须释放连接 httpClient.close(); } }
{"student":{"age":20,"birth":"2019-01-10T19:52:48.014+08:00","name":"韩哈哈哈","number":6666}}
import javax.ws.rs.*; import javax.ws.rs.core.MediaType; import java.sql.Date; import java.time.Instant; @Path("/rest") public class StudentServer { @Path("/student") @POST @Consumes("application/x-www-form-urlencoded") public String Student(@BeanParam Student student){ System.out.println(student); return "success:"+student.toString(); } }
import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; import java.io.IOException; import java.time.Instant; import java.util.ArrayList; import java.util.Date; import java.util.List; @SuppressWarnings("all") public class RestPostClientMain { public static void main(String[] args) throws ClientProtocolException, IOException { CloseableHttpClient httpClient = HttpClientBuilder.create().build(); HttpPost httpPost = new HttpPost("http://localhost:8080/studentServce/rest/student"); List<BasicNameValuePair> list = new ArrayList<BasicNameValuePair>(); list.add(new BasicNameValuePair("number", "0222")); list.add(new BasicNameValuePair("name", "张三")); list.add(new BasicNameValuePair("age", "19")); list.add(new BasicNameValuePair("birth", Date.from(Instant.now()).toString())) ; HttpEntity httpEntity = new UrlEncodedFormEntity(list, "utf-8"); httpPost.setEntity(httpEntity); HttpResponse httpResponse = httpClient.execute(httpPost); if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { HttpEntity entity = httpResponse.getEntity(); String result = EntityUtils.toString(entity, "utf-8"); System.out.println(result); EntityUtils.consume(entity); } else { System.err.println(httpResponse.getStatusLine()); } httpClient.close(); } }
//服务端打印
Student{number=222, name='张三', age=19, birth=Fri Jan 11 10:02:51 CST 2019}
//客户端打印
success:Student{number=222, name='张三', age=19, birth=Fri Jan 11 10:02:51 CST 2019}
整合步骤:
<dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>5.1.3.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>5.1.3.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>5.1.3.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>4.1.7.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> <version>5.1.3.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>5.1.3.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>5.1.3.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>5.1.3.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aspects</artifactId> <version>5.1.3.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>5.1.3.RELEASE</version> </dependency> <!-- 添加CXF dependency --> <!-- https://mvnrepository.com/artifact/org.apache.cxf/cxf-rt-frontend-jaxws --> <dependency> <groupId>org.apache.cxf</groupId> <artifactId>cxf-rt-frontend-jaxws</artifactId> <version>3.2.7</version> </dependency> <!-- https://mvnrepository.com/artifact/org.apache.cxf/cxf-rt-transports-http --> <dependency> <groupId>org.apache.cxf</groupId> <artifactId>cxf-rt-transports-http</artifactId> <version>3.2.7</version> </dependency> <!-- https://mvnrepository.com/artifact/org.apache.cxf/cxf-rt-frontend-jaxrs --> <dependency> <groupId>org.apache.cxf</groupId> <artifactId>cxf-rt-frontend-jaxrs</artifactId> <version>3.2.7</version> </dependency> <!-- https://mvnrepository.com/artifact/org.apache.cxf/cxf-rt-transports-http-jetty --> <dependency> <groupId>org.apache.cxf</groupId> <artifactId>cxf-rt-transports-http-jetty</artifactId> <version>3.2.7</version> </dependency> <!--没有这两个依赖会:No message body writer has been found for class com.hgx.web.service.restful.bean.Student, ContentType: application/json--> <!--https://mvnrepository.com/artifact/org.apache.cxf/cxf-rt-rs-extension-providers--> <dependency> <groupId>org.apache.cxf</groupId> <artifactId>cxf-rt-rs-extension-providers</artifactId> <version>3.2.7</version> </dependency> <!-- https://mvnrepository.com/artifact/org.codehaus.jettison/jettison --> <dependency> <groupId>org.codehaus.jettison</groupId> <artifactId>jettison</artifactId> <version>1.4.0</version> </dependency> <!--解决rest风格的api没有wadl--> <!-- https://mvnrepository.com/artifact/org.apache.cxf/cxf-rt-rs-service-description --> <dependency> <groupId>org.apache.cxf</groupId> <artifactId>cxf-rt-rs-service-description</artifactId> <version>3.2.7</version> </dependency> <!-- https://mvnrepository.com/artifact/com.google.code.gson/gson --> <dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.8.5</version> </dependency> </dependencies>
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebResult;
import javax.jws.WebService;
@WebService
public interface HelloWorld {
@WebMethod
@WebResult(name = "sayHelloResult")
String sayHello(@WebParam(name = "userName") String name, @WebParam(name = "userAge") int age);
}
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebResult;
public class HelloWorldImpl implements HelloWorld {
@Override
@WebMethod
@WebResult(name = "sayHelloResult")
public String sayHello(@WebParam(name = "userName") String name, @WebParam(name = "userAge") int age) {
return "spring say hello to: " + name + "\t" + "age: " + age;
}
}
package com.hgx.web.service.spring.service; import com.google.gson.Gson; import com.hgx.web.service.spring.entity.Customer; import javax.ws.rs.*; @Path("/crm") public class CustomerService { @GET @Path("/customer/{customer_id}") @Produces("application/json") public Customer getCustomerById(@PathParam("customer_id") String customer_id) { Customer customer = new Customer(customer_id, "z3", 18); return customer; } @POST @Path("/addcustomer") @Consumes("application/json") @Produces("application/json") public String addCustomer(String customer_json) { Gson gson = new Gson(); Customer customer = (Customer) gson.fromJson(customer_json, Customer.class); System.out.println(customer); return "success: " + customer.toString(); } }
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jaxws="http://cxf.apache.org/jaxws" xmlns:jaxrs="http://cxf.apache.org/jaxrs" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd http://cxf.apache.org/jaxrs http://cxf.apache.org/schemas/jaxrs.xsd"> <import resource="classpath:META-INF/cxf/cxf.xml"/> <jaxws:endpoint id="helloworld" implementor="com.hgx.web.service.spring.cxf.HelloWorldImpl" address="/HelloWorld"></jaxws:endpoint> <!--注意:坑爹的idea 导入的jaxrs-common.xsd不正确 应该是jaxrs.xsd --> <jaxrs:server id="customerService" address="/CustService"> <jaxrs:serviceBeans> <bean class="com.hgx.web.service.spring.service.CustomerService"/> </jaxrs:serviceBeans> </jaxrs:server> </beans>
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1"> <!-- 配置 Spring 配置文件的名称和位置 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:application-cxf.xml</param-value> </context-param> <!-- 启动 IOC 容器的 ServletContextListener --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!--webservice --> <servlet> <display-name>spring-cxf</display-name> <servlet-name>spring-cxf</servlet-name> <servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>spring-cxf</servlet-name> <url-pattern>/*</url-pattern> </servlet-mapping> <!--webservice--> </web-app>
public static void main(String[] args) { //wsdl地址 Client client = initClient("http://localhost:8080/spring_cxf_war/HelloWorld?wsdl"); try { // 方法 参数1 参数2 Object[] result = client.invoke("sayHello", "哈哈哈哈", 18); String outParam = ""; System.out.println(result.length); if (result.length > 0) { Object object = result[0]; if (object instanceof byte[]) { outParam = new String((byte[]) object); } else { outParam = (String) object; } } System.out.println(outParam); } catch (Exception e) { e.printStackTrace(); } } public static Client initClient(String url) { JaxWsDynamicClientFactory dcf = JaxWsDynamicClientFactory.newInstance(); Client client = dcf.createClient(url); //如果需要密码 //client.getOutInterceptors().add(new ClientLoginInterceptor("123","123")); HTTPConduit http = (HTTPConduit) client.getConduit(); HTTPClientPolicy httpClientPolicy = new HTTPClientPolicy(); httpClientPolicy.setConnectionTimeout(30000); httpClientPolicy.setAllowChunking(false); httpClientPolicy.setReceiveTimeout(60000); http.setClient(httpClientPolicy); return client; }
import org.apache.cxf.binding.soap.SoapMessage; import org.apache.cxf.headers.Header; import org.apache.cxf.helpers.DOMUtils; import org.apache.cxf.interceptor.Fault; import org.apache.cxf.phase.AbstractPhaseInterceptor; import org.apache.cxf.phase.Phase; import org.w3c.dom.Document; import org.w3c.dom.Element; import javax.xml.namespace.QName; import java.util.List; public class ClientLoginInterceptor extends AbstractPhaseInterceptor<SoapMessage> { public ClientLoginInterceptor(String username, String password) { super(Phase.PREPARE_SEND); this.username = username; this.password = password; } private String username; private String password; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public void handleMessage(SoapMessage soap) throws Fault { List<Header> headers = soap.getHeaders(); Document doc = DOMUtils.createDocument(); Element auth = doc.createElement("authrity"); Element username = doc.createElement("username"); Element password = doc.createElement("password"); username.setTextContent(this.username); password.setTextContent(this.password); auth.appendChild(username); auth.appendChild(password); headers.add(0, new Header(new QName("tiamaes"), auth)); } }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。