webservice restful接口跟soap协议的接口实现大同小异,只是在提供服务的类/接口的注解上存在差异,具体看下面的代码,然后自己对比下就可以了。

用到的基础类

User.java

 @XmlRootElement(name="User")
public class User { private String userName;
private String sex;
private int age; public User(String userName, String sex, int age) {
super();
this.userName = userName;
this.sex = sex;
this.age = age;
} public User() {
super();
} public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
} public static void main(String[] args) throws IOException {
System.setProperty("http.proxySet", "true"); System.setProperty("http.proxyHost", "192.168.1.20"); System.setProperty("http.proxyPort", "8080"); URL url = new URL("http://www.baidu.com"); URLConnection con =url.openConnection(); System.out.println(con);
}
}

接下来是服务提供类,PhopuRestfulService.java

 @Path("/phopuService")
public class PhopuRestfulService { Logger logger = Logger.getLogger(PhopuRestfulServiceImpl.class); @GET
@Produces(MediaType.APPLICATION_JSON) //指定返回数据的类型 json字符串
//@Consumes(MediaType.TEXT_PLAIN) //指定请求数据的类型 文本字符串
@Path("/getUser/{userId}")
public User getUser(@PathParam("userId")String userId) {
this.logger.info("Call getUser() method...."+userId);
User user = new User();
user.setUserName("中文");
user.setAge(26);
user.setSex("m");
return user;
} @POST
@Produces(MediaType.APPLICATION_JSON) //指定返回数据的类型 json字符串
//@Consumes(MediaType.TEXT_PLAIN) //指定请求数据的类型 文本字符串
@Path("/getUserPost")
public User getUserPost(String userId) {
this.logger.info("Call getUserPost() method...."+userId);
User user = new User();
user.setUserName("中文");
user.setAge(26);
user.setSex("m");
return user;
}
}

web.xml配置,跟soap协议的接口一样

 <!-- CXF webservice 配置 -->
<servlet>
<servlet-name>cxf-phopu</servlet-name>
<servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>cxf-phopu</servlet-name>
<url-pattern>/services/*</url-pattern>
</servlet-mapping>

Spring整合配置

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:p="http://www.springframework.org/schema/p"
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-3.0.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" />
<import resource="classpath:/META-INF/cxf/cxf-servlet.xml" />
<import resource="classpath:/META-INF/cxf/cxf-extension-soap.xml" /> <!-- 配置restful json 解析器 , 用CXF自带的JSONProvider需要注意以下几点
-1、dropRootElement 默认为false,则Json格式会将类名作为第一个节点,如{Customer:{"id":123,"name":"John"}},如果配置为true,则Json格式为{"id":123,"name":"John"}。
-2、dropCollectionWrapperElement属性默认为false,则当遇到Collection时,Json会在集合中将容器中类名作为一个节点,比如{"Customer":{{"id":123,"name":"John"}}},而设置为false,则JSon格式为{{"id":123,"name":"John"}}
-3、serializeAsArray属性默认为false,则当遇到Collecion时,格式为{{"id":123,"name":"John"}},如果设置为true,则格式为[{"id":123,"name":"john"}],而Gson等解析为后者 <bean id="jsonProviders" class="org.apache.cxf.jaxrs.provider.json.JSONProvider">
<property name="dropRootElement" value="true" />
<property name="dropCollectionWrapperElement" value="true" />
<property name="serializeAsArray" value="true" />
</bean>
-->
<!-- 服务类 -->
<bean id="phopuService" class="com.phopu.service.PhopuRestfulService" />
<jaxrs:server id="service" address="/">
<jaxrs:inInterceptors>
<bean class="org.apache.cxf.interceptor.LoggingInInterceptor" />
</jaxrs:inInterceptors>
<!--serviceBeans:暴露的WebService服务类-->
<jaxrs:serviceBeans>
<ref bean="phopuService" />
</jaxrs:serviceBeans>
<!--支持的协议-->
<jaxrs:extensionMappings>
<entry key="json" value="application/json"/>
<entry key="xml" value="application/xml" />
<entry key="text" value="text/plain" />
</jaxrs:extensionMappings>
<!--对象转换-->
<jaxrs:providers>
<!-- <ref bean="jsonProviders" /> 这个地方直接用CXF的对象转换器会存在问题,当接口发布,第一次访问没问题,但是在访问服务就会报错,等后续在研究下 -->
<bean class="org.codehaus.jackson.jaxrs.JacksonJaxbJsonProvider" />
</jaxrs:providers>
</jaxrs:server> </beans>

客户端调用示例:

对于get方式的服务,直接在浏览器中输入 http://localhost:8080/phopu/services/phopuService/getUser/101010500 就可以直接看到返回的json字符串

{"userName":"中文","sex":"m","age":26}

客户端调用代码如下:

 public static void getWeatherPostTest() throws Exception{
String url = "http://localhost:8080/phopu/services/phopuService/getUserPost";
HttpClient httpClient = HttpClients.createSystem();
//HttpGet httpGet = new HttpGet(url); //接口get请求,post not allowed
HttpPost httpPost = new HttpPost(url);
httpPost.addHeader(CONTENT_TYPE_NAME, "text/plain");
StringEntity se = new StringEntity("101010500");
se.setContentType("text/plain");
httpPost.setEntity(se);
HttpResponse response = httpClient.execute(httpPost); int status = response.getStatusLine().getStatusCode();
log.info("[接口返回状态吗] : " + status); String weatherInfo = ClientUtil.getReturnStr(response); log.info("[接口返回信息] : " + weatherInfo);
}

客户端调用返回信息如下:

ClientUtil类是我自己封装的一个读取response返回信息的类,encoding是UTF-8

 public static String getReturnStr(HttpResponse response) throws Exception {
String result = null;
BufferedInputStream buffer = new BufferedInputStream(response.getEntity().getContent());
byte[] bytes = new byte[1024];
int line = 0;
StringBuilder builder = new StringBuilder();
while ((line = buffer.read(bytes)) != -1) {
builder.append(new String(bytes, 0, line, HTTP_SERVER_ENCODING));
}
result = builder.toString();
return result;
}

到这里,就介绍完了,大家手动去操作一下吧,有问题大家一块交流。

Spring整合CXF webservice restful 实例的更多相关文章

  1. Spring整合CXF,发布RSETful 风格WebService(转)

    Spring整合CXF,发布RSETful 风格WebService 这篇文章是承接之前CXF整合Spring的这个项目示例的延伸,所以有很大一部分都是一样的.关于发布CXF WebServer和Sp ...

  2. Spring整合CXF,发布RSETful 风格WebService

    原文地址:http://www.cnblogs.com/hoojo/archive/2012/07/23/2605219.html 这篇文章是承接之前CXF整合Spring的这个项目示例的延伸,所以有 ...

  3. Spring整合CXF之发布WebService服务

    今天我们来讲下如何用Spring来整合CXF,来发布WebService服务: 给下官方文档地址:http://cxf.apache.org/docs/writing-a-service-with-s ...

  4. Spring整合CXF步骤,Spring实现webService,spring整合WebService

    Spring整合CXF步骤 Spring实现webService, spring整合WebService >>>>>>>>>>>> ...

  5. Java WebService 教程系列之 Spring 整合 CXF

    Java WebService 教程系列之 Spring 整合 CXF 一.引入 jar 包 <dependency> <groupId>org.apache.cxf</ ...

  6. 【jersey】 spring 整合jersey 实现RESTful webservice

         Jersey是一个RESTFUL请求服务JAVA框架,与常规的JAVA编程使用的struts框架类似,它主要用于处理业务逻辑层.与Struts类似,它同样可以和hibernate,sprin ...

  7. Spring boot 整合CXF webservice 遇到的问题及解决

    将WebService的WSDL生成的代码的命令: wsimport -p com -s . com http://localhost:8080/service/user?wsdl Spring bo ...

  8. So easy Webservice 8.spring整合CXF 发布WS

    1.添加jar包(cxf的jar包中包含了spring的jar包),添加spring配置文件 2.web.xml中配置CXFServlet,过滤WS服务的地址 <!-- 配置CXFServlet ...

  9. Spring整合CXF发布及调用WebService

    这几天终于把webService搞定,下面给大家分享一下发布webService和调用webService的方法 添加jar包 (官方下载地址:http://cxf.apache.org/downlo ...

随机推荐

  1. error: open of glibc-devel-2.12-1.132.el6.i686.rpm failed: 没有那个文件或目录

    在安装qt的时候出现了错误: error: open of glibc-devel-2.12-1.132.el6.i686.rpm failed: 没有那个文件或目录 错误原因:缺少glibc-dev ...

  2. iOS 输入限制之 InputKit

    前言 最近接手了两个 O2O 的老项目,其中的 Bug 也不言而喻,单看项目中的布局就有 n 种不同的方式,有用纯代码的,有用 Masonry 的,有用 VFL 的,也有用 Xib 的,更有用代码约束 ...

  3. 【LeetCode】187. Repeated DNA Sequences

    题目: All DNA is composed of a series of nucleotides abbreviated as A, C, G, and T, for example: " ...

  4. H5仿微信界面教程(一)

    前言 先来张图,仿微信界面,界面如下,并不完全一模一样,只能说有些类似,希望大家见谅. 1 用到的知识点 jQuery WeUI 是WeUI的一个jQuery实现版本,除了实现了官方插件之外,它还提供 ...

  5. Wireshark网络端点和会话

    如果想让网络进行正常通信,你必须至少拥有两台设备进行数据流交互.端点(endpoint)就是指网络上能够发送和接受数据的一台设备.举例来说,在TCP/IP的通信中就有两个断电:接收和发送数据系统的IP ...

  6. MessageBoxButtons.OKCancel的选择事件

    private void 退出ToolStripMenuItem1_Click(object sender, EventArgs e) { DialogResult resault = Message ...

  7. 如何删除 SQL Server 表中的重复行

    第一种:有主键的重复行,就是说主键不重复,但是记录的内容重复比如人员表tab ,主键列id,身份证编号idcard当身份证重复的时候,保留最小id值的记录,其他删除delete a from tab ...

  8. linux系统编程之文件IO

    1.打开文件的函数open,第一个参数表示文件路径名,第二个为打开标记,第三个为文件权限 代码: #include <sys/types.h> #include <sys/stat. ...

  9. 在linux中安装git,并将代码发布到github

    楼主Git小白,今天刚刚学习了git,虽然在工作中也许用不到,但是在学习的时候肯定会用到的,毕竟一个程序员首先就要整理自己的知识点,将美丽的代码分享与大家. 楼主是将Git安装在阿里云的centos7 ...

  10. spark-2.2.0安装和部署——Spark集群学习日记

    前言 在安装后hadoop之后,接下来需要安装的就是Spark. scala-2.11.7下载与安装 具体步骤参见上一篇博文 Spark下载 为了方便,我直接是进入到了/usr/local文件夹下面进 ...