Java CXF RestFul风格的web service发布与调用

xiaoxiao2021-02-28  72

优点:

Ø Ø Restful 风格的 web service 是直接通过 http 协议通信。       所以,可以直接通过浏览器访问服务方法       相对于 soap 格式的 web service 更快,不愈要声称客户端代码。

一、发布:

Ø 导入依赖 jar Ø 定制 RetFul 风格的 web service Ø web service 纳入工厂 Ø Web.xml 中配置CXFServlet 1、 定制 RestFul 风格的 web service

2、web service纳入工厂

3、Web.xml中配置CXFServlet

4、在浏览器输入网址直接返回json串:

二、调用:

1、通过 apache HttpClient的Fluent发起http请求调用,导入jar, 则在项目中需要调用 RestFul web 服务的位置可以 使用上述文件中的api,即通过以上支持,已然可以在项目的任意一个位置调用  RestFul的Web-Service 2、调用实例:先建立一个测试类,下面是各种方式的例子。

//get

@Test public void testHTTP() throws ClientProtocolException, IOException{ System.out.println(Request.Get("http://localhost:8989/ws_cxf_spring_rest/rest/wsRest/rest9/query/xxx")         .execute().returnContent().asString()); } //post @Test public void testHTTP2() throws ClientProtocolException, IOException{ System.out.println(Request.Post("http://localhost:8989/ws_cxf_spring_rest/rest/wsRest/rest9/insert")        .body(new StringEntity("{\"user9\":{\"id\":99,\"name\":\"zhj9\"}}"))         .setHeader("content-type", "application/json")         .execute()); } /** *   实体的@XmlRootElement为"user9" *  .body(new StringEntity("{\"user9\":{\"id\":88,\"name\":\"zhj88\"}}")) *  换了provider后 *   .body(new StringEntity("{\"id\":88,\"name\":\"zhj88\"}")) * @throws ClientProtocolException * @throws IOException */

//put @Test public void testHTTP3() throws ClientProtocolException, IOException{ System.out.println(Request.Put("http://localhost:8989/ws_cxf_spring_rest/rest/wsRest/rest9/update")        .body(new StringEntity("{\"id\":88,\"name\":\"zhj88\"}"))         .setHeader("content-type", "application/json")         .execute().returnContent().asString()); }

//delete @Test

public void testHTTP4() throws ClientProtocolException, IOException{ System.out.println(Request.Delete("http://localhost:8989/ws_cxf_spring_rest/rest/wsRest/rest9/delete/11")         .execute().returnContent().asString()); }

转载请注明原文地址: https://www.6miu.com/read-77463.html

最新回复(0)