一、restful web services

  rest全称是Representation State Transfer(表述性状态转移)。它是一种软件架构风格,只是提供了一组设计原则和约束条件。在restful web services的设计原则中,所有的事物都应该拥有唯一的URI,通过对URI的请求访问,完成相应的操作。访问的方法与http协议中的若干方法相对应。如下:

  • 创建资源,使用 POST 方法。
  • 获取某个资源,使用 GET 方法。
  • 对资源进行更新,使用 PUT 方法。
  • 删除某个资源,使用 DELETE 方法。

二、使用cxf进行构建

  1、服务器端

  新建工程,添加cxf的依赖jar包。添加netty-all依赖,这里使用到的是netty-all-4.0.25.Final,下载地址为:http://netty.io/downloads.html 。

  实体类Address:

  1. package com.cxf.jaxrs;
  2.  
  3. import javax.xml.bind.annotation.XmlRootElement;
  4.  
  5. @XmlRootElement(name = "address")
  6. public class Address {
  7.  
  8. private int id;
  9. private String city;
  10. private String street;
  11.  
  12. public int getId() {
  13. return id;
  14. }
  15.  
  16. public void setId(int id) {
  17. this.id = id;
  18. }
  19.  
  20. public String getCity() {
  21. return city;
  22. }
  23.  
  24. public void setCity(String city) {
  25. this.city = city;
  26. }
  27.  
  28. public String getStreet() {
  29. return street;
  30. }
  31.  
  32. public void setStreet(String street) {
  33. this.street = street;
  34. }
  35.  
  36. }

  实体类Person:

  1. package com.cxf.jaxrs;
  2.  
  3. import java.util.Date;
  4.  
  5. import javax.xml.bind.annotation.XmlRootElement;
  6.  
  7. @XmlRootElement(name = "person")
  8. public class Person {
  9.  
  10. private int id;
  11. private String name;
  12. private Date date;
  13.  
  14. private Address address;
  15.  
  16. public int getId() {
  17. return id;
  18. }
  19.  
  20. public void setId(int id) {
  21. this.id = id;
  22. }
  23.  
  24. public String getName() {
  25. return name;
  26. }
  27.  
  28. public void setName(String name) {
  29. this.name = name;
  30. }
  31.  
  32. public Date getDate() {
  33. return date;
  34. }
  35.  
  36. public void setDate(Date date) {
  37. this.date = date;
  38. }
  39.  
  40. public Address getAddress() {
  41. return address;
  42. }
  43.  
  44. public void setAddress(Address address) {
  45. this.address = address;
  46. }
  47.  
  48. }

  服务接口MyService:

  1. package com.cxf.jaxrs;
  2.  
  3. import java.util.Date;
  4. import java.util.List;
  5.  
  6. import javax.ws.rs.DELETE;
  7. import javax.ws.rs.GET;
  8. import javax.ws.rs.POST;
  9. import javax.ws.rs.PUT;
  10. import javax.ws.rs.Path;
  11. import javax.ws.rs.PathParam;
  12. import javax.ws.rs.Produces;
  13.  
  14. @Path("/person/")
  15. // @Produces("text/xml") //只返回xml类型
  16. // @Produces("application/json") //只返回json类型
  17. @Produces("*/*") //表示可返回所有类型
  18. public class MyService {
  19.  
  20. @GET //get方法请求
  21. @Path("/{id}/") //路径
  22. public Person getById(@PathParam("id") int id) {
  23. Person person = new Person();
  24. person.setId(id);
  25. person.setName("zhangsan");
  26. person.setDate(new Date());
  27.  
  28. Address add = new Address();
  29. add.setId(22);
  30. add.setCity("shanghai");
  31. add.setStreet("pudong");
  32. person.setAddress(add);
  33.  
  34. return person;
  35. }
  36.  
  37. @GET //get方法请求
  38. @Path("/") //路径
  39. public List<Person> getAll() {
  40. List<Person> persons = new java.util.ArrayList<Person>();
  41. Person person = new Person();
  42. person.setId(111);
  43. person.setName("zhangsan");
  44. person.setDate(new Date());
  45.  
  46. Person person2 = new Person();
  47. person2.setId(222);
  48. person2.setName("lisi");
  49. person2.setDate(new Date());
  50. persons.add(person);
  51. persons.add(person2);
  52. return persons;
  53. }
  54.  
  55. @DELETE //delete方法请求
  56. @Path("/{id}") //路径
  57. public Person removeById(@PathParam("id") int id) {
  58. Person person = new Person();
  59. person.setId(111);
  60. person.setName("zhangsan");
  61. person.setDate(new Date());
  62. return person;
  63. }
  64.  
  65. @POST //post方法请求
  66. @Path("/") //路径
  67. public Person add(Person person) {
  68. System.out.println(person.getDate());
  69. return person;
  70. }
  71.  
  72. @PUT //put方法请求
  73. @Path("/{id}/") //路径
  74. public Person update(@PathParam("id") int id, Person person) {
  75. System.out.println("put id : " + id);
  76. System.out.println(person.getDate());
  77. return person;
  78. }
  79. }

  对于服务类,我们也可定义一个接口,在接口里面写annotation,再定义一个实现类,实现类之完成具体业务逻辑。这样也是可以的。

  服务器启动类Server:

  1. package com.cxf.jaxrs;
  2.  
  3. import org.apache.cxf.interceptor.LoggingInInterceptor;
  4. import org.apache.cxf.interceptor.LoggingOutInterceptor;
  5. import org.apache.cxf.jaxrs.JAXRSServerFactoryBean;
  6. import org.apache.cxf.jaxrs.lifecycle.SingletonResourceProvider;
  7.  
  8. public class Server {
  9. public static void main(String[] args) {
  10.  
  11. JAXRSServerFactoryBean factoryBean = new JAXRSServerFactoryBean();
  12. factoryBean.setAddress("http://localhost:9000/myservice");
  13.  
  14. factoryBean.setResourceClasses(MyService.class);
  15. factoryBean.setResourceProvider(MyService.class,
  16. new SingletonResourceProvider(new MyService()));
  17. factoryBean.getInInterceptors().add(new LoggingInInterceptor());
  18. factoryBean.getOutInterceptors().add(new LoggingOutInterceptor());
  19. factoryBean.create();
  20. }
  21. }

  2、客户端

  对于客户端访问,使用apache的httpclient进行请求。cxf的lib目录总已经有httpclient jar包,这里可以直接使用。

  访问代码如下:

  1. package com.cxf.jaxrs;
  2.  
  3. import java.io.IOException;
  4. import java.io.InputStream;
  5. import java.io.StringWriter;
  6. import java.text.SimpleDateFormat;
  7. import java.util.Date;
  8.  
  9. import javax.xml.parsers.DocumentBuilder;
  10. import javax.xml.parsers.DocumentBuilderFactory;
  11. import javax.xml.parsers.ParserConfigurationException;
  12. import javax.xml.transform.OutputKeys;
  13. import javax.xml.transform.TransformerFactory;
  14. import javax.xml.transform.TransformerFactoryConfigurationError;
  15. import javax.xml.transform.dom.DOMSource;
  16. import javax.xml.transform.stream.StreamResult;
  17.  
  18. import org.apache.cxf.helpers.IOUtils;
  19. import org.apache.cxf.io.CachedOutputStream;
  20. import org.apache.http.HttpEntity;
  21. import org.apache.http.HttpStatus;
  22. import org.apache.http.client.ClientProtocolException;
  23. import org.apache.http.client.methods.CloseableHttpResponse;
  24. import org.apache.http.client.methods.HttpDelete;
  25. import org.apache.http.client.methods.HttpGet;
  26. import org.apache.http.client.methods.HttpPost;
  27. import org.apache.http.client.methods.HttpPut;
  28. import org.apache.http.entity.ContentType;
  29. import org.apache.http.entity.StringEntity;
  30. import org.apache.http.impl.client.CloseableHttpClient;
  31. import org.apache.http.impl.client.HttpClients;
  32. import org.apache.http.util.EntityUtils;
  33. import org.w3c.dom.Document;
  34. import org.w3c.dom.Element;
  35.  
  36. public class Client {
  37.  
  38. public static SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
  39.  
  40. public static void main(String[] args) throws Exception {
  41.  
  42. System.out.println("===========================get by url =================================");
  43. String getResult = get("http://localhost:9000/myservice/person/1");
  44. System.out.println(getResult);
  45.  
  46. System.out.println("===========================get===================================");
  47. String getsResult = get("http://localhost:9000/myservice/person");
  48. System.out.println(getsResult);
  49.  
  50. System.out.println("===========================delete===================================");
  51. String deleteResult = delete("http://localhost:9000/myservice/person/1");
  52. System.out.println(deleteResult);
  53.  
  54. System.out.println("===========================post=================================");
  55. Person person = new Person();
  56. person.setId(3435);
  57. person.setName("lisi");
  58. person.setDate(new Date());
  59.  
  60. Document document = coverPersonToDocument(person);
  61.  
  62. String data = coverDocumentToString(document);
  63.  
  64. System.out.println("request data: ");
  65. System.out.println(data);
  66.  
  67. String postResult = post("http://localhost:9000/myservice/person", data);
  68. System.out.println("response data: ");
  69. System.out.println(postResult);
  70.  
  71. System.out.println("===========================put===================================");
  72. Person person2 = new Person();
  73. person2.setId(3435);
  74. person2.setName("lisi");
  75. person2.setDate(new Date());
  76.  
  77. document = coverPersonToDocument(person);
  78.  
  79. data = coverDocumentToString(document);
  80.  
  81. System.out.println("request data: ");
  82.  
  83. String putResult = put("http://localhost:9000/myservice/person/1", data);
  84. System.out.println("response data: ");
  85. System.out.println(putResult);
  86.  
  87. }
  88.  
  89. /**
  90. * 发送get 方法请求,并返回结果
  91. * @param url
  92. * @return
  93. * @throws IOException
  94. * @throws ParserConfigurationException
  95. */
  96. private static String get(String url) throws IOException,
  97. ParserConfigurationException {
  98. HttpGet get = new HttpGet(url);
  99. get.setHeader("Accept", "application/json");//接受json数据返回类型
  100. CloseableHttpClient client = HttpClients.createDefault();
  101. String responseContent = null;
  102. CloseableHttpResponse response = null;
  103. try {
  104. response = client.execute(get);
  105. HttpEntity entity = response.getEntity();//响应体
  106. if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {//响应状态码
  107. responseContent = EntityUtils.toString(entity, "UTF-8");
  108. }
  109. } catch (ClientProtocolException e) {
  110. e.printStackTrace();
  111. }
  112.  
  113. return responseContent;
  114. }
  115.  
  116. /**
  117. * 发送delete 方法请求,并返回结果
  118. * @param url
  119. * @return
  120. * @throws IOException
  121. * @throws ParserConfigurationException
  122. */
  123. private static String delete(String url) throws IOException,
  124. ParserConfigurationException {
  125. HttpDelete delete = new HttpDelete(url);
  126. CloseableHttpClient client = HttpClients.createDefault();
  127. CloseableHttpResponse response = null;
  128. String responseContent = null;
  129. try {
  130. response = client.execute(delete);
  131. HttpEntity entity = response.getEntity();//响应体
  132. if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {//响应状态码
  133. responseContent = EntityUtils.toString(entity, "UTF-8");
  134. }
  135. } catch (ClientProtocolException e) {
  136. e.printStackTrace();
  137. }
  138. return responseContent;
  139. }
  140.  
  141. /**
  142. * 发送post 方法请求,并返回结果
  143. * @param url
  144. * @param data
  145. * @return
  146. * @throws IOException
  147. * @throws ParserConfigurationException
  148. */
  149. private static String post(String url, String data) throws IOException,
  150. ParserConfigurationException {
  151. HttpPost post = new HttpPost(url);
  152.  
  153. StringEntity myEntity = new StringEntity(data,
  154. ContentType.APPLICATION_XML);//请求体数据,xml类型
  155. post.setEntity(myEntity);
  156.  
  157. CloseableHttpClient client = HttpClients.createDefault();
  158. String responseContent = null;
  159. CloseableHttpResponse response = null;
  160. try {
  161. response = client.execute(post);
  162. HttpEntity entity = response.getEntity();//响应体
  163. if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {//响应状态码
  164. responseContent = EntityUtils.toString(entity, "UTF-8");
  165. }
  166. } catch (ClientProtocolException e) {
  167. e.printStackTrace();
  168. }
  169. return responseContent;
  170. }
  171.  
  172. /**
  173. * 发送put 方法请求,并返回结果
  174. * @param url
  175. * @param data
  176. * @return
  177. * @throws ParserConfigurationException
  178. * @throws IOException
  179. */
  180. private static String put(String url, String data)
  181. throws ParserConfigurationException, IOException {
  182. HttpPut put = new HttpPut(url);
  183. StringEntity myEntity = new StringEntity(data,
  184. ContentType.APPLICATION_XML);
  185. put.setEntity(myEntity);
  186. put.setHeader("Accept", "application/json");//接受json数据返回类型
  187. CloseableHttpClient client = HttpClients.createDefault();
  188. String responseContent = null;
  189. CloseableHttpResponse response = null;
  190. try {
  191. response = client.execute(put);
  192. HttpEntity entity = response.getEntity();//响应体
  193. if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {//响应状态码
  194. responseContent = EntityUtils.toString(entity, "UTF-8");
  195. }
  196. } catch (ClientProtocolException e) {
  197. e.printStackTrace();
  198. }
  199. return responseContent;
  200. }
  201.  
  202. /**
  203. * 使用对象构造xml文档对象,并返回
  204. * @param person
  205. * @return
  206. * @throws ParserConfigurationException
  207. */
  208. private static Document coverPersonToDocument(Person person)
  209. throws ParserConfigurationException {
  210. DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
  211. DocumentBuilder builder = factory.newDocumentBuilder();
  212. Document document = builder.newDocument();
  213. Element root = document.createElement("person");
  214. Element node = document.createElement("id");
  215. node.setTextContent(String.valueOf(person.getId()));
  216.  
  217. Element node2 = document.createElement("name");
  218. node2.setTextContent(person.getName());
  219.  
  220. Element node3 = document.createElement("date");
  221. node3.setTextContent(format.format(person.getDate()));
  222.  
  223. root.appendChild(node);
  224. root.appendChild(node2);
  225. root.appendChild(node3);
  226.  
  227. document.appendChild(root);
  228. return document;
  229. }
  230.  
  231. /**
  232. * 将xml文档对象转换成String,并返回
  233. * @param document
  234. * @return
  235. * @throws TransformerFactoryConfigurationError
  236. */
  237. private static String coverDocumentToString(Document document)
  238. throws TransformerFactoryConfigurationError {
  239. StreamResult strResult = new StreamResult(new StringWriter());
  240. TransformerFactory tfac = TransformerFactory.newInstance();
  241. try {
  242. javax.xml.transform.Transformer t = tfac.newTransformer();
  243. t.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
  244. t.setOutputProperty(OutputKeys.INDENT, "yes");
  245. t.setOutputProperty(OutputKeys.METHOD, "xml"); // xml, html,
  246. t.transform(new DOMSource(document.getDocumentElement()), strResult);
  247. } catch (Exception e) {
  248. System.err.println("XML.toString(Document): " + e);
  249. }
  250. String data = strResult.getWriter().toString();
  251. return data;
  252. }
  253. }

  请求的结果如下:

cxf开发Restful Web Services的更多相关文章

  1. 使用 Spring 3 来创建 RESTful Web Services

    来源于:https://www.ibm.com/developerworks/cn/web/wa-spring3webserv/ 在 Java™ 中,您可以使用以下几种方法来创建 RESTful We ...

  2. 使用 Spring 3 来创建 RESTful Web Services(转)

    使用 Spring 3 来创建 RESTful Web Services 在 Java™ 中,您可以使用以下几种方法来创建 RESTful Web Service:使用 JSR 311(311)及其参 ...

  3. Spring 3 来创建 RESTful Web Services

    Spring 3 创建 RESTful Web Services 在 Java™ 中,您可以使用以下几种方法来创建 RESTful Web Service:使用 JSR 311(311)及其参考实现 ...

  4. Spring 4 集成Apache CXF开发JAX-RS Web Service

    什么是JAX-RS 在JSR-311规范中定义,即Java API for RESTful Web Services,一套Java API,用于开发 RESTful风格的Webservice. 工程概 ...

  5. 使用CXF开发RESTFul服务

    相信大家在阅读CXF官方文档(http://cxf.apache.org/docs/index.html)时,总是一知半解.这里向大家推荐一本PacktPub.Apache.CXF.Web.Servi ...

  6. 用Jersey为Android客户端开发Restful Web Service

    平时在做Android客户端的时候经常要与服务器之间通信,客户端通过服务端提供的接口获取数据,然后再展示在客户端的界面上,作为Android开发者,我们平时更多的是关注客户端的开发,而对服务端开发的关 ...

  7. RESTful Web Services初探

    RESTful Web Services初探 作者:杜刚 近几年,RESTful Web Services渐渐开始流行,大量用于解决异构系统间的通信问题.很多网站和应用提供的API,都是基于RESTf ...

  8. RESTful Web Services测试工具推荐

    命令行控的最爱:cURL cURL是一个很强大的支持各种协议的文件传输工具,用它来进行RESTful Web Services的测试简直是小菜一碟.这个工具基本上类Unix操作系统(各种Linux.M ...

  9. 【转】RESTful Web Services初探

    近几年,RESTful Web Services渐渐开始流行,大量用于解决异构系统间的通信问题.很多网站和应用提供的API,都是基于RESTful风格的Web Services,比较著名的包括Twit ...

随机推荐

  1. SQL Server 诊断查询-(4)

    Query #41 Memory Clerk Usage -- Memory Clerk Usage for instance -- Look for high value for CACHESTOR ...

  2. Sprint第三个冲刺(第二天)

    一.Sprint介绍 任务进度: 二.Sprint周期 看板: 燃尽图:

  3. C#调用webservice 时如何传递实体对象

    在webservice端公开一个实体类,然后实例化,赋值,然后再给到webservice,可以实现,但是,即使调用端和service端的实体类完全一致,你也要重新实例化service端的,重新赋值,将 ...

  4. myeclipse的实用快捷键

    (1)Ctrl+M切换窗口的大小(2)Ctrl+Q跳到最后一次的编辑处(3)F2当鼠标放在一个标记处出现Tooltip时候按F2则把鼠标移开时Tooltip还会显示即Show Tooltip Desc ...

  5. SQL Server 性能调优(一)——从等待状态判断系统资源瓶颈【转】

    转载自:http://blog.csdn.net/dba_huangzj/article/details/7607844#comments 通过DMV查看当时SQL SERVER所有任务的状态(sle ...

  6. python中的__init__ 、__new__、__call__小结

    这篇文章主要介绍了python中的__init__ .__new__.__call__小结,需要的朋友可以参考下 1.__new__(cls, *args, **kwargs)  创建对象时调用,返回 ...

  7. UGUI之Toggle使用

    Toggle对象是一个开关.一般用于单选,可以用Toggle制作背包的选项卡 在场景中创建Toggle按钮.看看他有Toggle组件

  8. 泛函编程(14)-try to map them all

    虽然明白泛函编程风格中最重要的就是对一个管子里的元素进行操作.这个管子就是这么一个东西:F[A],我们说F是一个针对元素A的高阶类型,其实F就是一个装载A类型元素的管子,A类型是相对低阶,或者说是基础 ...

  9. mysql max_allowed_packet过小导致的prepare失败

    最近公司一台阿里云上模拟环境突然好好地就出错了额,总提示:"Unknown prepared statement handler (stmt) given to DEALLOCATE PRE ...

  10. JavaScripts 基础详细笔记整理

    一.JS简介 JavaScript 是 Web 的编程语言,浏览器内置了JavaScript语言的解释器,所以在浏览器上按照JavaScript语言的规则编写相应代码之,浏览器可以解释并做出相应的处理 ...