您的位置:首页 > 其它

CXF实现webService之restful风格的RS模式

2017-12-28 11:23 344 查看

CXF实现webService之restful风格的RS模式

由于网上对这方面的介绍相对少一些,我就说一下.这里我用的是springboot来做的.

1.首先,客户端,服务端都要依赖的pom

<dependency>

    <groupId>org.springframework.boot</groupId>

    <artifactId>spring-boot-starter-jersey</artifactId>

    <version>1.5.9.RELEASE</version>

</dependency>

2.服务端配置

说明:服务端配置一个bean,这个bean就是servlet,并指明了访问根路径为/rest,和包路径。

@Bean

//servlet容器

public ServletRegistrationBean jerseyServlet() {

//创建servlet并指明访问路径

ServletRegistrationBean
registration = new ServletRegistrationBean(new ServletContainer(),"/rest/*");

//包路径
registration.addInitParameter("jersey.config.server.provider.packages","com.guanghan.service");

return registration;

}

 

2. 客户端调用代码

     说明:http://localhost:8088/rest/xc/ff中的rest是servlet中配置的,xc是服务暴露接口配置的,ff是restful的风格的参数。

GET请求

 WebTarget base =ClientBuilder.newClient().target("http://localhost:8088/rest/xc/ff");

        Integer
userlist = base.request(javax.ws.rs.core.MediaType.APPLICATION_JSON).get(new GenericType<Integer>()
{ });

POST请求一(JSON形式请求)

WebTarget base =ClientBuilder.newClient().target("http://localhost:8088/rest/ee");

Response invoke = request.post(Entity.entity(user, MediaType.APPLICATION_JSON));

POST请求二(表单形式请求)

WebTarget base =ClientBuilder.newClient().target("http://localhost:8088/rest/rr");

Form f = new Form();

f.param("t", currentTimeMillis+"");

f.param("data", data);

Response invoke = request.post(Entity.entity(f, MediaType.APPLICATION_FORM_URLENCODED));

客户端也可以实现以json形式调用接口,并且可以模仿表单提交(另一种方式)

 

3.暴露的服务接口

@Produces("*/*")

@Path("/")

public class method{

@Path("/xc/{arr}")

@GET()

@Produces({"application/json"})

@Consumes({"application/xml","application/json"})

public int getf(@PathParam("arr")
String arr) {

System.out.println(arr);

return 3;

}

}

像restful这类服务接口还有很多,像springcloud中的服务发现和服务发布这个模块就用的了这个方式
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: