`
zangwenyang
  • 浏览: 127746 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

使用Jersey构建rest接口

    博客分类:
  • java
 
阅读更多

原文地址http://www.vogella.com/articles/REST/article.html

从rest最基本的知识开始介绍,有介绍的jersey的开发过程,简单易学十分推荐

 

原文内容:

RESTful Webservices with Java (Jersey / JAX-RS)

This tutorial explains how to develop RESTful web services in Java with the JAX-RS reference implementation Jersey.

In this tutorial Eclipse 3.6 (Helios), Java 1.6, Tomcat 6.0 and JAX-RS 1.1. (Jersey 1.5) is used.


1. REST - Representational State Transfer

1.1. Overview

REST is an architectural style which is based on web-standards and the HTTP protocol. REST was first described by Roy Fielding in 2000.

In a REST based architecture everything is a resource. A resource is accessed via a common interface based on the HTTP standard methods. In an REST architecture you typically have a REST server which provides access to the resources and a REST client which accesses and modify the REST resources. Every resource should support the HTTP common operations. Resources are identified by global IDs (which are typically URIs).

REST allows that resources have different representations, e.g. text, xml, json etc. The rest client can ask for specific representation via the HTTP protocol (Content Negotiation).

1.2. HTTP methods

The HTTP standards methods which are typical used in REST are PUT, GET, POST, DELETE.

  • GET defines a reading access of the resource without side-effects. The resource is never changed via a GET request, e.g. the request has no side effects (idempotent).

  • PUT creates a new resource, must also be idempotent.

  • DELETE removes the resources. The operations are idempotent, they can get repeated without leading to different results.

  • POST updates an existing resource or creates a new resource.

 

1.3. RESTFul webservices

A RESTFul webservices is based on the HTTP methods and the concept of REST. It typically defines the base URI for the services, the MIME-types its supports (XML, Text, JSON, user-defined,..) and the set of operations (POST, GET, PUT, DELETE) which are supported. JAX-RS supports the creation of XML and JSON via JAXB.

1.4. Java, REST and Jersey

Java defines standard REST support via JAX-RS (The Java API for RESTful Web Services) in JSR 311.JAX-RS uses annotations to define the REST relevance of classes.

Via your web.xml you will register a servlet provided by Jersey and also define the path under which your REST web application will be available. The base URL of this servlet is:

 

http://your_domain:port/display-name/url-pattern/path_from_rest_class 

This servlet which analyze the incoming HTTP request and select the correct class and method to respond to this request. This selection is based on annotation in the class and methods.

The most important annotations in JAX-RS are the following.

Table 1. Sample Table

Annotation Description
@PATH(your_path) Sets the path to base URL + /your_path. The base URL is based on your application name, the servlet and the URL pattern from the web.xml" configuration file.
@POST Indicates that the following method will answer to a HTTP POST request
@GET Indicates that the following method will answer to a HTTP GET request
@PUT Indicates that the following method will answer to a HTTP PUT request
@DELETE Indicates that the following method will answer to a HTTP DELETE request
@Produces(MediaType.TEXT_PLAIN [, more-types ]) @Produces defines which MIME type is delivered by a method annotated with @GET. In the example text ("text/plain") is produced. Other examples would be "application/xml" or "application/json".
@Consumes(type [, more-types ]) @Consumes defines which MIME type is consumed by this method.
@PathParam Used to inject values from the URL into a method parameter. This way you inject for example the ID of a resource into the method to get the correct object.


The complete path to a resource is therefore based on the base URL and the @PATh annotation in your class.

 

http://your_domain:port/display-name/url-pattern/path_from_rest_class 

Jerseyis the reference implementation for this specification. Jersey contains basically a REST server and a REST client. The core client is mainly available for testing and provides a library to communicate with the server.

A REST web application consists of data classes (resources) and services. These two types are typically maintained in different packages as the Jersey servlet will be instructed via the web.xmlto scan certain packages for data classes.

2. Installation

2.1. Jersey

Download Jersey from Jersey Homepage . As of the time of writing the file is called A zip of Jersey containing the Jersey jars, core dependencies (it does not provide dependencies for third party jars beyond the those for JSON support) and JavaDoc." Download this zip; it contains the jar files required for the REST functionality.

2.2. Eclipse and Tomcat

This tutorial is using Tomcat as servlet container and Eclipse WTP as a development environment. Please see Eclipse WTP and Apache Tomcat for instructions on how to install and use Eclipse WTP and Apache Tomcat.

Alternative you could also use the Google App Engine for running the server part of the following REST examples. If you use the Google App Engine you do not have to setup Tomcat. If you are using GAE/J you have to create App Engine projects instead of "Dynamic Web Project".

3. Create your first RESTful Webservice

3.1. Create project

Create a new "Dynamic Web Project" "de.vogella.jersey.first". See Eclipse WTP development for how to create a new dynamic web project.

 

 

Copy all jars from your Jersey download into the folder "WEB-INF/lib".

3.2. Java Class

Create the following class.

 

package de.vogella.jersey.first;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

// POJO, no interface no extends

// The class registers its methods for the HTTP GET request using the @GET annotation. 
// Using the @Produces annotation, it defines that it can deliver several MIME types,
// text, XML and HTML. 

// The browser requests per default the HTML MIME type.

//Sets the path to base URL + /hello
@Path("/hello")
public class Hello {

  // This method is called if TEXT_PLAIN is request
  @GET
  @Produces(MediaType.TEXT_PLAIN)
  public String sayPlainTextHello() {
    return "Hello Jersey";
  }

  // This method is called if XML is request
  @GET
  @Produces(MediaType.TEXT_XML)
  public String sayXMLHello() {
    return "<?xml version=\"1.0\"?>" + "<hello> Hello Jersey" + "</hello>";
  }

  // This method is called if HTML is request
  @GET
  @Produces(MediaType.TEXT_HTML)
  public String sayHtmlHello() {
    return "<html> " + "<title>" + "Hello Jersey" + "</title>"
        + "<body><h1>" + "Hello Jersey" + "</body></h1>" + "</html> ";
  }

} 

 

This class register itself as a get resource via the @GET annotation. Via the @Produces annotation it defines that it delivers two MIME types, "text" and "HTML" code. It also defines via the "Path" annotation that its service should be available under the URL "hello".

The browser will always request the html MIME type. To see the text version you can use tool like curl .

3.3. Define Jersey Servlet dispatcher

You need to register Jersey as the servlet dispatcher for REST requests. Open the file web.xml and modify the file to the following.

 

<?xml version="1.0" encoding="UTF-8"?>
<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">
  <display-name>de.vogella.jersey.first</display-name>
  <servlet>
    <servlet-name>Jersey REST Service</servlet-name>
    <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
    <init-param>
      <param-name>com.sun.jersey.config.property.packages</param-name>
      <param-value>de.vogella.jersey.first</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>Jersey REST Service</servlet-name>
    <url-pattern>/rest/*</url-pattern>
  </servlet-mapping>
</web-app> 

 

The parameter "com.sun.jersey.config.property.package" defines in which package jersey will look for the web service classes. This property must point to your resources classes. The URL pattern defines part of the base URL your application will be placed.

3.4. Run your rest service

Run you web application in Eclipse. See Eclipse WTP for details on how to run dynamic web applications.

Test your REST service under: "http://localhost:8080/de.vogella.jersey.first/rest/hello". This name is derived from the "display-name" defined in the web.xml file, augmented with the servlet-mapping url-pattern and the "hello" @Path annotation from your class file. You should get the message "Hello Jersey".

The browser requests the HTML representation of your resource. In the next chapter we are going to write a client which will read the XML representation.

3.5. Create a client

Jersey contains a REST client library which can be used for testing or to build a real client in Java. Alternative you could use Apache HttpClient to create a client.

Create a new Java "de.vogella.jersey.first.client" and add the jersey jars to the project and the project build path. Create the following test class.

 

package de.vogella.jersey.first.client;

import java.net.URI;

import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.UriBuilder;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;

public class Test {
  public static void main(String[] args) {
    ClientConfig config = new DefaultClientConfig();
    Client client = Client.create(config);
    WebResource service = client.resource(getBaseURI());
    // Fluent interfaces
    System.out.println(service.path("rest").path("hello").accept(MediaType.TEXT_PLAIN).get(ClientResponse.class).toString());
    // Get plain text
    System.out.println(service.path("rest").path("hello").accept(MediaType.TEXT_PLAIN).get(String.class));
    // Get XML
    System.out.println(service.path("rest").path("hello").accept(MediaType.TEXT_XML).get(String.class));
    // The HTML
    System.out.println(service.path("rest").path("hello").accept(MediaType.TEXT_HTML).get(String.class));

  }

  private static URI getBaseURI() {
    return UriBuilder.fromUri("http://localhost:8080/de.vogella.jersey.first").build();
  }

} 

 

4. Restful webservices and JAXB

JAX-RS supports the automatic creation of XML and JSON via JAXB. For an introduction into XML please see Java and XML - Tutorial . For an introduction into JAXB please see JAXB. You can continue this tutorial without reading these tutorials but they contain more background information.

4.1. Create project

Create a new "Dynamic Web Project" "de.vogella.jersey.jaxb" and copy all jersey jars into the folder "WEB-INF/lib".

Create your domain class.

 

package de.vogella.jersey.jaxb.model;

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
// JAX-RS supports an automatic mapping from JAXB annotated class to XML and JSON
// Isn't that cool?
public class Todo {
  private String summary;
  private String description;
  public String getSummary() {
    return summary;
  }
  public void setSummary(String summary) {
    this.summary = summary;
  }
  public String getDescription() {
    return description;
  }
  public void setDescription(String description) {
    this.description = description;
  }

  
} 

 

Create the following resource class. This class simply return an instance of the Todo class.

 

package de.vogella.jersey.jaxb;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

import de.vogella.jersey.jaxb.model.Todo;

@Path("/todo")
public class TodoResource {
  // This method is called if XMLis request
  @GET
  @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
  public Todo getXML() {
    Todo todo = new Todo();
    todo.setSummary("This is my first todo");
    todo.setDescription("This is my first todo");
    return todo;
  }
  
  // This can be used to test the integration with the browser
  @GET
  @Produces({ MediaType.TEXT_XML })
  public Todo getHTML() {
    Todo todo = new Todo();
    todo.setSummary("This is my first todo");
    todo.setDescription("This is my first todo");
    return todo;
  }

} 

 

Change web.xml to the following.

 

<?xml version="1.0" encoding="UTF-8"?>
<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">
  <display-name>de.vogella.jersey.jaxb</display-name>
  <servlet>
    <servlet-name>Jersey REST Service</servlet-name>
    <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
    <init-param>
      <param-name>com.sun.jersey.config.property.packages</param-name>
      <param-value>de.vogella.jersey.jaxb</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>Jersey REST Service</servlet-name>
    <url-pattern>/rest/*</url-pattern>
  </servlet-mapping>
</web-app> 

 

Run you web application in Eclipse and validate that you can access your service. Your application should be available under "http://localhost:8080/de.vogella.jersey.jaxb/rest/todo".

4.2. Create a client

Create a new Java "de.vogella.jersey.jaxb.client" and add the jersey jars to the project and the project build path. Create the following test class.

 

package de.vogella.jersey.jaxb.client;


import java.net.URI;

import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.UriBuilder;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;

public class Test {
  public static void main(String[] args) {
    ClientConfig config = new DefaultClientConfig();
    Client client = Client.create(config);
    WebResource service = client.resource(getBaseURI());
    // Get XML
    System.out.println(service.path("rest").path("todo").accept(MediaType.TEXT_XML).get(String.class));
    // Get XML for application
    System.out.println(service.path("rest").path("todo").accept(MediaType.APPLICATION_JSON).get(String.class));
    // Get JSON for application
    System.out.println(service.path("rest").path("todo").accept(MediaType.APPLICATION_XML).get(String.class));
  }

  private static URI getBaseURI() {
    return UriBuilder.fromUri("http://localhost:8080/de.vogella.jersey.jaxb").build();
  }

} 

 

5. CRUD RESTful webservice

This section creates a CRUD (Create, Read, Update, Delete) restful web service. It will allow to maintain a list of todos in your web application via HTTP calls.

5.1. Project

Create a new dynamic project called de.vogella.jersey.todo and add the jersey libs. Change the web.xmlfile to the following.

 

<?xml version="1.0" encoding="UTF-8"?>
<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">
  <display-name>de.vogella.jersey.todo</display-name>
  <servlet>
    <servlet-name>Jersey REST Service</servlet-name>
    <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
    <init-param>
      <param-name>com.sun.jersey.config.property.packages</param-name>
      <param-value>de.vogella.jersey.todo.resources</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>Jersey REST Service</servlet-name>
    <url-pattern>/rest/*</url-pattern>
  </servlet-mapping>
</web-app> 

 

Create the following data model and a Singleton which serves as the data provider for the model. We use the implementation based on an enumeration. Please see the link for details. The Todo class is annotated with a JAXB annotation. See Java and XML to learn about JAXB.

 

package de.vogella.jersey.todo.model;


import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class Todo {
  private String id;
  private String summary;
  private String description;
  
  public Todo(){
    
  }
  public Todo (String id, String summary){
    this.id = id;
    this.summary = summary;
  }
  public String getId() {
    return id;
  }
  public void setId(String id) {
    this.id = id;
  }
  public String getSummary() {
    return summary;
  }
  public void setSummary(String summary) {
    this.summary = summary;
  }
  public String getDescription() {
    return description;
  }
  public void setDescription(String description) {
    this.description = description;
  }
  
  
} 

 

 

package de.vogella.jersey.todo.dao;

import java.util.HashMap;
import java.util.Map;

import de.vogella.jersey.todo.model.Todo;

public enum TodoDao {
  instance;
  
  private Map<String, Todo> contentProvider = new HashMap<String, Todo>();
  
  private TodoDao() {
    
    Todo todo = new Todo("1", "Learn REST");
    todo.setDescription("Read http://www.vogella.com/articles/REST/article.html");
    contentProvider.put("1", todo);
    todo = new Todo("2", "Do something");
    todo.setDescription("Read complete http://www.vogella.com");
    contentProvider.put("2", todo);
    
  }
  public Map<String, Todo> getModel(){
    return contentProvider;
  }
  
} 

 

5.2. Create a simple HTML form

The rest service can be used via HTML forms. The following HTML form will allow to post new data to the service. Create the following page called create_todo.html in the WEB-INF folder.

 

<!DOCTYPE html>
<html>
 <head>
  <title>Form to create a new resource</title>
 </head>
<body>
  <form action="../de.vogella.jersey.todo/rest/todos" method="POST">
  <label for="id">ID</label>
  <input name="id" />
  <br/>
  <label for="summary">Summary</label>
  <input name="summary" />
  <br/>
  Description:
  <TEXTAREA NAME="description" COLS=40 ROWS=6></TEXTAREA>
  <br/>
  <input type="submit" value="Submit" />
  </form>
</body>
</html> 

 

5.3. Rest Service

Create the following classes which will be used as REST resources.

 

package de.vogella.jersey.todo.resources;

import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.PUT;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Request;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
import javax.xml.bind.JAXBElement;

import de.vogella.jersey.todo.dao.TodoDao;
import de.vogella.jersey.todo.model.Todo;

public class TodoResource {
  @Context
  UriInfo uriInfo;
  @Context
  Request request;
  String id;
  public TodoResource(UriInfo uriInfo, Request request, String id) {
    this.uriInfo = uriInfo;
    this.request = request;
    this.id = id;
  }
  
  //Application integration     
  @GET
  @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
  public Todo getTodo() {
    Todo todo = TodoDao.instance.getModel().get(id);
    if(todo==null)
      throw new RuntimeException("Get: Todo with " + id +  " not found");
    return todo;
  }
  
  // For the browser
  @GET
  @Produces(MediaType.TEXT_XML)
  public Todo getTodoHTML() {
    Todo todo = TodoDao.instance.getModel().get(id);
    if(todo==null)
      throw new RuntimeException("Get: Todo with " + id +  " not found");
    return todo;
  }
  
  @PUT
  @Consumes(MediaType.APPLICATION_XML)
  public Response putTodo(JAXBElement<Todo> todo) {
    Todo c = todo.getValue();
    return putAndGetResponse(c);
  }
  
  @DELETE
  public void deleteTodo() {
    Todo c = TodoDao.instance.getModel().remove(id);
    if(c==null)
      throw new RuntimeException("Delete: Todo with " + id +  " not found");
  }
  
  private Response putAndGetResponse(Todo todo) {
    Response res;
    if(TodoDao.instance.getModel().containsKey(todo.getId())) {
      res = Response.noContent().build();
    } else {
      res = Response.created(uriInfo.getAbsolutePath()).build();
    }
    TodoDao.instance.getModel().put(todo.getId(), todo);
    return res;
  }
  
  

} 

 

 

package de.vogella.jersey.todo.resources;


import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.Consumes;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Request;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;

import de.vogella.jersey.todo.dao.TodoDao;
import de.vogella.jersey.todo.model.Todo;


// Will map the resource to the URL todos
@Path("/todos")
public class TodosResource {

  // Allows to insert contextual objects into the class, 
  // e.g. ServletContext, Request, Response, UriInfo
  @Context
  UriInfo uriInfo;
  @Context
  Request request;


  // Return the list of todos to the user in the browser
  @GET
  @Produces(MediaType.TEXT_XML)
  public List<Todo> getTodosBrowser() {
    List<Todo> todos = new ArrayList<Todo>();
    todos.addAll(TodoDao.instance.getModel().values());
    return todos; 
  }
  
  // Return the list of todos for applications
  @GET
  @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
  public List<Todo> getTodos() {
    List<Todo> todos = new ArrayList<Todo>();
    todos.addAll(TodoDao.instance.getModel().values());
    return todos; 
  }
  
  
  // retuns the number of todos
  // Use http://localhost:8080/de.vogella.jersey.todo/rest/todos/count
  // to get the total number of records
  @GET
  @Path("count")
  @Produces(MediaType.TEXT_PLAIN)
  public String getCount() {
    int count = TodoDao.instance.getModel().size();
    return String.valueOf(count);
  }
  
  @POST
  @Produces(MediaType.TEXT_HTML)
  @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
  public void newTodo(@FormParam("id") String id,
      @FormParam("summary") String summary,
      @FormParam("description") String description,
      @Context HttpServletResponse servletResponse) throws IOException {
    Todo todo = new Todo(id,summary);
    if (description!=null){
      todo.setDescription(description);
    }
    TodoDao.instance.getModel().put(id, todo);
    
    servletResponse.sendRedirect("../create_todo.html");
  }
  
  
  // Defines that the next path parameter after todos is
  // treated as a parameter and passed to the TodoResources
  // Allows to type http://localhost:8080/de.vogella.jersey.todo/rest/todos/1
  // 1 will be treaded as parameter todo and passed to TodoResource
  @Path("{todo}")
  public TodoResource getTodo(@PathParam("todo") String id) {
    return new TodoResource(uriInfo, request, id);
  }
  
} 

 

This TodosResource uses the @PathParam "annotation to define that the id is inserted as parameter.

5.4. Run

Run you web application in Eclipse and test the availability of your REST service under: "http://localhost:8080/de.vogella.jersey.todo/rest/todos". You should see the XML representation of your Todo items.

 

 

To see the count of Todo items use "http://localhost:8080/de.vogella.jersey.todo/rest/todos/count" to see an exiting todo use "http://localhost:8080/de.vogella.jersey.todo/rest/todos/{id}", e.g. "http://localhost:8080/de.vogella.jersey.todo/rest/todos/1" to see the todo with ID 1. We currently have only todos with the id's 1 and 2, all other requests will result an HTTP error code.

Please note that with the browser you can only issue HTTP GET requests. The next chapter will use the jersey client libraries to issue get, post and delete.

5.5. Create a client

Create a new Java project called de.vogella.jersey.todo.client. Create a lib folder and place all jersey libs in this folder. Add the jars to the classpath of the project.

Create the following class.

 

package de.vogella.jersey.todo.client;

import java.net.URI;

import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.UriBuilder;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
import com.sun.jersey.api.representation.Form;

import de.vogella.jersey.todo.model.Todo;

public class Tester {
  public static void main(String[] args) {
    ClientConfig config = new DefaultClientConfig();
    Client client = Client.create(config);
    WebResource service = client.resource(getBaseURI());
    // Create one todo
    Todo todo = new Todo("3", "Blabla");
    ClientResponse response = service.path("rest").path("todos")
        .path(todo.getId()).accept(MediaType.APPLICATION_XML)
        .put(ClientResponse.class, todo);
    // Return code should be 201 == created resource
    System.out.println(response.getStatus());
    // Get the Todos
    System.out.println(service.path("rest").path("todos")
        .accept(MediaType.TEXT_XML).get(String.class));
    // Get JSON for application
    System.out.println(service.path("rest").path("todos")
        .accept(MediaType.APPLICATION_JSON).get(String.class));
    // Get XML for application
    System.out.println(service.path("rest").path("todos")
        .accept(MediaType.APPLICATION_XML).get(String.class));

    // Get the Todo with id 1
    System.out.println(service.path("rest").path("todos/1")
        .accept(MediaType.APPLICATION_XML).get(String.class));
    // get Todo with id 1
    service.path("rest").path("todos/1").delete();
    // Get the all todos, id 1 should be deleted
    System.out.println(service.path("rest").path("todos")
        .accept(MediaType.APPLICATION_XML).get(String.class));

    // Create a Todo
    Form form = new Form();
    form.add("id", "4");
    form.add("summary", "Demonstration of the client lib for forms");
    response = service.path("rest").path("todos")
        .type(MediaType.APPLICATION_FORM_URLENCODED)
        .post(ClientResponse.class, form);
    System.out.println("Form response " + response.getEntity(String.class));
    // Get the all todos, id 4 should be created
    System.out.println(service.path("rest").path("todos")
        .accept(MediaType.APPLICATION_XML).get(String.class));

  }

  private static URI getBaseURI() {
    return UriBuilder.fromUri("http://localhost:8080/de.vogella.jersey.todo").build();
  }
} 

 

5.6. Using the rest service via HTML page

The above example contains a form which calls a post method of your rest service.

5.7. Using the rest service via X

Usually every programming language provide somewhere libraries for creating HTTP get, post, put and delete requests. For Java the project Apache HttpClient.

6. Thank you

 

 

Please help me to support this article:

Flattr this  

 

7. Questions and Discussion

Before posting questions, please see the vogella FAQ. If you have questions or find an error in this article please use the www.vogella.com Google Group. I have created a short list how to create good questions which might also help you.

8. Links and Literature

8.1. Source Code

Source Code of Examples

8.2. Rest Resources

http://jersey.java.net/ Jersey Homepage

http://www.ibm.com/developerworks/library/wa-aj-tomcat/ IBM Article about Rest with Tomcat and Jersey

8.3. vogella Resources

vogella Training Android and Eclipse Training from the vogella team

Android Tutorial Introduction to Android Programming

GWT Tutorial Program in Java and compile to JavaScript and HTML

Eclipse RCP Tutorial Create native applications in Java

JUnit Tutorial Test your application

Git Tutorial Put everything you have under distributed version control system

分享到:
评论

相关推荐

    jersey构建rest服务,通过mybatis访问数据库

    本篇文章将深入探讨如何使用Jersey构建REST服务,并结合MyBatis实现数据库访问。 首先,我们需要理解REST(Representational State Transfer)的核心概念,它是基于资源的架构风格,使用HTTP方法如GET、POST、PUT、...

    动态发布rest接口及服务调用

    总的来说,"动态发布REST接口及服务调用"涵盖了使用Jetty和Jersey在Java中构建RESTful服务的基本流程,从接口的定义、发布到调用的全过程。通过这种方式,开发者可以快速地开发和测试REST服务,为分布式系统提供灵活...

    使用jersey构建RESTful Web服务

    总之,使用Jersey构建RESTful Web服务,可以遵循JAX-RS标准,利用其强大的注解和API,快速开发出高效且易于维护的服务。同时,结合`RestfulClient`和`RestfulServer`这两个示例,你可以更好地理解和掌握RESTful服务...

    致远OA开发REST远程接口实现发送表单

    3. **发起请求**:使用Java的HTTP客户端库,如Apache HttpClient或者Java内置的HttpURLConnection,向配置好的REST接口发送请求。在这个过程中,你需要设置HTTP头信息,比如Content-Type(通常为application/json)...

    Jersey-rest服务的Jar包1.8.2版本,含源代码

    6. `jersey-client-1.18.2.jar`:客户端库,用于构建发送 REST 请求的客户端。 7. `jersey-servlet-1.18.2.jar`:Servlet 容器插件,使得 Jersey 能够部署在支持 Servlet 的服务器上。 8. `jersey-client-1.18.2-...

    Java调rest接口依赖包

    使用jersey调用REST接口的基本步骤如下: 1. 引入jersey依赖:在项目中添加jersey的相关jar包或依赖项,对于Maven项目,可以在pom.xml中配置jersey的依赖。 2. 创建`Client`对象:`Client client = ClientBuilder....

    jersey rest web services整理

    这篇博文主要涵盖了使用Jersey构建REST服务的关键知识点。 首先,理解REST(Representational State Transfer)的核心原则至关重要。REST强调资源的概念,通过HTTP方法(GET、POST、PUT、DELETE等)来操作这些资源...

    构建Restful Web服务-jersey

    本篇文章将深入探讨如何使用Jersey构建RESTful Web服务。 首先,了解RESTful的基本概念至关重要。REST(Representational State Transfer)是一种网络应用程序的设计风格和开发方式,强调通过HTTP协议进行数据传输...

    java Rest 接口

    1. **使用HTTP方法进行操作**:REST接口使用HTTP的四种主要方法——GET、POST、PUT和DELETE,分别对应获取资源、创建新资源、更新资源和删除资源的操作。这些方法可以直接通过URL和HTTP头来识别,无需在请求内容中...

    REST相关jar包

    REST(Representational State Transfer,表述性状态转移)是一种软件...了解这些库的作用和使用方式,对于开发、调试和维护REST接口至关重要。通过熟练掌握这些工具,开发者能够高效地构建和管理高质量的RESTful服务。

    rest jersey 所必须的jar包

    在使用Jersey构建REST服务时,有几个关键的JAR包是必不可少的。这些JAR包提供了Jersey的核心功能,包括路由处理、HTTP请求/响应的处理、JSON和XML的序列化与反序列化等。以下是关于这些JAR包的详细说明: 1. **jax...

    REST的开源框架jersey

    Jersey作为JAX-RS的实现,提供了完整的工具集和运行时环境,使得开发者可以轻松地将这些注解应用到Java类和方法上,从而构建REST服务。 ### 2. Jersey核心概念 - **资源类(Resource Class)**:使用`@Path`注解...

    jersey1.18 jar包

    该描述提到"rest接口所使用的jar包及相关文档",意味着这个压缩包不仅包含了jar包,还可能包括相关的API文档或用户指南,帮助开发者理解和使用Jersey来构建REST接口。Jersey官网提供的包通常会包含最新的更新和修复...

    基于rest的jersey实现webservice

    **基于REST的Jersey实现Web服务** REST(Representational State Transfer)是一种软件架构风格,用于构建Web服务。它强调简洁、可伸缩性和基于HTTP协议的设计。RESTful Web服务使用HTTP方法(如GET、POST、PUT、...

    rest接口实例

    在Java中,我们可以使用JAX-RS库如Jersey或Apache CXF来实现REST接口。以Jersey为例,我们首先需要在项目中引入依赖: ```xml &lt;groupId&gt;javax.ws.rs &lt;artifactId&gt;javax.ws.rs-api &lt;version&gt;2.1 &lt;groupId&gt;org...

    Equinox OSGi应用嵌入Jersey框架搭建REST服务

    - 使用Java注解来定义REST服务接口。例如,你可以使用`@Path`注解来指定资源路径,`@GET`, `@POST`等来定义HTTP方法,以及`@Produces`和`@Consumes`来指定输入和输出的MIME类型。 ```java @Path("/hello") public ...

    利用spring整合jersey和Protobuf,搭建REST web服务

    3. 集成Spring和Jersey:配置Spring容器,创建Jersey资源类,使用注解定义REST端点。 4. 实现业务逻辑:在资源类中处理请求,使用Protobuf进行数据序列化和反序列化。 5. 创建Python客户端:导入Python的protobuf库...

    jersey-core、jersey-client jar包.rar

    标题中的"jersey-core、jersey-client jar包.rar"指的是两个关键的Java库,它们是Jersey框架的核心...通过jersey-core和jersey-client,开发者能够构建出强大的、能够与任何支持REST接口的服务器进行交互的应用程序。

Global site tag (gtag.js) - Google Analytics