【转】RESTful Webservice创建

RESTful Web Services with Java

 
REST stands for REpresentational State Transfer, was first introduced by Roy Fielding in his thesis"Architectural Styles and the Design of Network-based Software Architectures" in year 2000.

REST is an architectural style. HTTP is a protocol which contains the set of REST architectural constraints.

REST fundamentals

  • Everything in REST is considered as a resource.
  • Every resource is identified by an URI.
  • Uses uniform interfaces. Resources are handled using POST, GET, PUT, DELETE operations which are similar to Create, Read, update and Delete(CRUD) operations.
  • Be stateless. Every request is an independent request. Each request from client to server must contain all the information necessary to understand the request.
  • Communications are done via representations. E.g. XML, JSON

RESTful Web Services

RESTful Web Services have embraced by large service providers across the web as an alternative to SOAP based Web Services due to its simplicity. This post will demonstrate how to create a RESTful Web Service and client using Jersey framework which extends JAX-RS API. Examples are done using Eclipse IDE and Java SE 6.

Creating RESTful Web Service

    • In Eclipse, create a new dynamic web project called "RESTfulWS"
【转】RESTful Webservice创建
    • Download Jersey zip bundle from here. Jersey version used in these examples is 1.17.1. Once you unzip it you'll have a directory called "jersey-archive-1.17.1". Inside it find the lib directory. Copy following jars from there and paste them inside WEB-INF -> lib folder in your project. Once you've done that, add those jars to your project build path as well.
      1. asm-3.1.jar
      2. jersey-client-1.17.1.jar
      3. jersey-core-1.17.1.jar
      4. jersey-server-1.17.1.jar
      5. jersey-servlet-1.17.1.jar
      6. jsr311-api-1.1.1.jar
【转】RESTful Webservice创建
【转】RESTful Webservice创建
    • In your project, inside Java Resources -> src create a new package called "com.eviac.blog.restws". Inside it create a new java class called "UserInfo". Also include the given web.xml file inside WEB-INF folder.

UserInfo.java

  1. package com.eviac.blog.restws;
  2. import javax.ws.rs.GET;
  3. import javax.ws.rs.Path;
  4. import javax.ws.rs.PathParam;
  5. import javax.ws.rs.Produces;
  6. import javax.ws.rs.core.MediaType;
  7. /**
  8. *
  9. * @author pavithra
  10. *
  11. */
  12. // @Path here defines class level path. Identifies the URI path that
  13. // a resource class will serve requests for.
  14. @Path("UserInfoService")
  15. public class UserInfo {
  16. // @GET here defines, this method will method will process HTTP GET
  17. // requests.
  18. @GET
  19. // @Path here defines method level path. Identifies the URI path that a
  20. // resource class method will serve requests for.
  21. @Path("/name/{i}")
  22. // @Produces here defines the media type(s) that the methods
  23. // of a resource class can produce.
  24. @Produces(MediaType.TEXT_XML)
  25. // @PathParam injects the value of URI parameter that defined in @Path
  26. // expression, into the method.
  27. public String userName(@PathParam("i") String i) {
  28. String name = i;
  29. return "<User>" + "<Name>" + name + "</Name>" + "</User>";
  30. }
  31. @GET
  32. @Path("/age/{j}")
  33. @Produces(MediaType.TEXT_XML)
  34. public String userAge(@PathParam("j") int j) {
  35. int age = j;
  36. return "<User>" + "<Age>" + age + "</Age>" + "</User>";
  37. }
  38. }

web.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  3. <display-name>RESTfulWS</display-name>
  4. <servlet>
  5. <servlet-name>Jersey REST Service</servlet-name>
  6. <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
  7. <init-param>
  8. <param-name>com.sun.jersey.config.property.packages</param-name>
  9. <param-value>com.eviac.blog.restws</param-value>
  10. </init-param>
  11. <load-on-startup>1</load-on-startup>
  12. </servlet>
  13. <servlet-mapping>
  14. <servlet-name>Jersey REST Service</servlet-name>
  15. <url-pattern>/rest/*</url-pattern>
  16. </servlet-mapping>
  17. </web-app>
    • To run the project, right click on it and click on run as ->run on server.
    • Execute the following URL in your browser and you'll see the output.
      1. http://localhost:8080/RESTfulWS/rest/UserInfoService/name/Pavithra
【转】RESTful Webservice创建

output

【转】RESTful Webservice创建

Creating Client

    • Create a package called "com.eviac.blog.restclient". Inside it create a java class called "UserInfoClient".

UserInfoClient.java

  1. package com.eviac.blog.restclient;
  2. import javax.ws.rs.core.MediaType;
  3. import com.sun.jersey.api.client.Client;
  4. import com.sun.jersey.api.client.ClientResponse;
  5. import com.sun.jersey.api.client.WebResource;
  6. import com.sun.jersey.api.client.config.ClientConfig;
  7. import com.sun.jersey.api.client.config.DefaultClientConfig;
  8. /**
  9. *
  10. * @author pavithra
  11. *
  12. */
  13. public class UserInfoClient {
  14. public static final String BASE_URI = "http://localhost:8080/RESTfulWS";
  15. public static final String PATH_NAME = "/UserInfoService/name/";
  16. public static final String PATH_AGE = "/UserInfoService/age/";
  17. public static void main(String[] args) {
  18. String name = "Pavithra";
  19. int age = 25;
  20. ClientConfig config = new DefaultClientConfig();
  21. Client client = Client.create(config);
  22. WebResource resource = client.resource(BASE_URI);
  23. WebResource nameResource = resource.path("rest").path(PATH_NAME + name);
  24. System.out.println("Client Response \n"
  25. + getClientResponse(nameResource));
  26. System.out.println("Response \n" + getResponse(nameResource) + "\n\n");
  27. WebResource ageResource = resource.path("rest").path(PATH_AGE + age);
  28. System.out.println("Client Response \n"
  29. + getClientResponse(ageResource));
  30. System.out.println("Response \n" + getResponse(ageResource));
  31. }
  32. /**
  33. * Returns client response.
  34. * e.g :
  35. * GET http://localhost:8080/RESTfulWS/rest/UserInfoService/name/Pavithra
  36. * returned a response status of 200 OK
  37. *
  38. * @param service
  39. * @return
  40. */
  41. private static String getClientResponse(WebResource resource) {
  42. return resource.accept(MediaType.TEXT_XML).get(ClientResponse.class)
  43. .toString();
  44. }
  45. /**
  46. * Returns the response as XML
  47. * e.g : <User><Name>Pavithra</Name></User>
  48. *
  49. * @param service
  50. * @return
  51. */
  52. private static String getResponse(WebResource resource) {
  53. return resource.accept(MediaType.TEXT_XML).get(String.class);
  54. }
  55. }
    • Once you run the client program, you'll get following output.
  1. Client Response
  2. GET http://localhost:8080/RESTfulWS/rest/UserInfoService/name/Pavithra returned a response status of 200 OK
  3. Response
  4. <User><Name>Pavithra</Name></User>
  5. Client Response
  6. GET http://localhost:8080/RESTfulWS/rest/UserInfoService/age/25 returned a response status of 200 OK
  7. Response
  8. <User><Age>25</Age></User>

From: http://blog.eviac.com/2013/11/restful-web-services-with-java.html

 
上一篇:聊天平台源码,聊天平台如何获取到音频流


下一篇:python 提取视频中音频