最近在开发RESTful API,使用的是Jersey框架。引用百科:“Jersey RESTful 框架是开源的RESTful框架, 实现了JAX-RS (JSR 311 & JSR 339) 规范。它扩展了JAX-RS 参考实现, 提供了更多的特性和工具, 可以进一步地简化 RESTful service 和 client 开发。”网上关于Jersey的资料和实例很多,但是大多数是1.0版本,所以决定写个2.0版本的详细实例。
实例包括server和client,包括GET和POST(XML、JSON)方法。最后包括一个ApacheHttpClient的client程序。
Jersey Server
首先是pom文件
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>JERSEY_SERVER</groupId>
<artifactId>JERSEY_SERVER</artifactId>
<version>1.0</version>
<dependencies>
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-servlet</artifactId>
<version>2.20</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-server</artifactId>
<version>2.20</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.glassfish.jersey.containers/jersey-container-grizzly2-http -->
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-grizzly2-http</artifactId>
<version>2.20</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.3.5</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-annotations -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.3.5</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.jaxrs/jackson-jaxrs-json-provider -->
<dependency>
<groupId>com.fasterxml.jackson.jaxrs</groupId>
<artifactId>jackson-jaxrs-json-provider</artifactId>
<version>2.3.5</version>
</dependency>
</dependencies>
</project>
添加注册器,由于POST方法会使用JSON类型,所以注册JacksonJsonProvider
package jersey;
import org.glassfish.jersey.filter.LoggingFilter;
import org.glassfish.jersey.server.ResourceConfig;
import com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider;
public class APIApplication extends ResourceConfig{
public APIApplication() {
packages("jersey");
//加载Resource
register(RESTResource.class);
//注册数据转换器
register(JacksonJsonProvider.class);
// Logging.
register(LoggingFilter.class);
}
}
添加Server
package jersey;
import java.io.IOException;
import java.net.URI;
import org.glassfish.grizzly.http.server.HttpServer;
import org.glassfish.jersey.grizzly2.httpserver.GrizzlyHttpServerFactory;
public class JerseyServer {
public static final String BASE_URI = "http://localhost:8080/jerseyserver/";
public static HttpServer startServer() {
final APIApplication apiApplication = new APIApplication();
return GrizzlyHttpServerFactory.createHttpServer(URI.create(BASE_URI), apiApplication);
}
public static void main(String[] args) throws IOException {
final HttpServer server = startServer();
System.out.println("Jersey server started...\nHit enter to stop...");
System.in.read();
server.shutdownNow();
}
}
添加服务
package jersey;
import javax.ws.rs.Consumes;
import javax.ws.rs.PathParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
@Path("test")
public class RESTResource {
@GET
@Path("get/{param:[a-zA-Z0-9]*}")
@Consumes({MediaType.TEXT_PLAIN, MediaType.APPLICATION_JSON})
@Produces(MediaType.TEXT_PLAIN)
public String getResourceName(
@PathParam("param") String requestParam) {
System.out.println("****** HTTP request get******");
System.out.println(requestParam);
String responseStr ="test get result";
return responseStr;
}
@POST
@Path("postxml")
@Consumes(MediaType.APPLICATION_XML)
@Produces(MediaType.APPLICATION_XML)
public RESTResponse postXML(RESTRequest req) {
System.out.println("****** HTTP request post xml******");
System.out.println(req.getType());
System.out.println(req.getParam());
RESTResponse resp = new RESTResponse();
resp.setRespCode(0);
resp.setRespDesc("success");
resp.setResult("test result");
return resp;
}
@POST
@Path("postjson")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public RESTResponse postJSON(RESTRequest req) {
System.out.println("****** HTTP request post json******");
System.out.println(req.getType());
System.out.println(req.getParam());
RESTResponse resp = new RESTResponse();
resp.setRespCode(0);
resp.setRespDesc("success");
resp.setResult("test result");
return resp;
}
}
在服务中定义了两个类,由于POST方法会使用XML类型,所以添加@XmlRootElement注解,代码如下
package jersey;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class RESTRequest {
private String type;
private String param;
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getParam() {
return param;
}
public void setParam(String param) {
this.param = param;
}
}
package jersey;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class RESTResponse {
private int respCode;
private String respDesc;
private String result;
public int getRespCode() {
return respCode;
}
public void setRespCode(int respCode) {
this.respCode = respCode;
}
public String getRespDesc() {
return respDesc;
}
public void setRespDesc(String respDesc) {
this.respDesc = respDesc;
}
public String getResult() {
return result;
}
public void setResult(String result) {
this.result = result;
}
}
Jersey Client
首先添加pom文件<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>JERSEY_CLIENT</groupId>
<artifactId>JERSEY_CLIENT</artifactId>
<version>1.0</version>
<dependencies>
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-servlet-core</artifactId>
<version>2.0.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.glassfish.jersey.core/jersey-client -->
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-client</artifactId>
<version>2.0.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.3.5</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-annotations -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.3.5</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.jaxrs/jackson-jaxrs-json-provider -->
<dependency>
<groupId>com.fasterxml.jackson.jaxrs</groupId>
<artifactId>jackson-jaxrs-json-provider</artifactId>
<version>2.3.5</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.2</version>
</dependency>
</dependencies>
</project>
添加Server中的自定义类RESTRequest和RESTResponse。
添加调用方法
package jersey;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.Invocation;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.glassfish.jersey.client.ClientConfig;
import org.glassfish.jersey.filter.LoggingFilter;
public class JerseyClient {
public static void main(String[] args) {
//getScheduleJsonString();
//postRequestResponse();
//getTest();
//postXMLTest();
postJSONTest();
}
private static void getTest(){
Client client = ClientBuilder.newClient( new ClientConfig().register( LoggingFilter.class ) );
WebTarget webTarget = client.target("http://localhost:8080/jerseyserver/test/get/helloworld");
Invocation.Builder invocationBuilder = webTarget.request(MediaType.TEXT_PLAIN);
Response response = invocationBuilder.get();
String result = response.readEntity(String.class);
System.out.println(result);
}
private static void postXMLTest(){
Client client = ClientBuilder.newClient( new ClientConfig().register( LoggingFilter.class ) );
WebTarget webTarget = client.target("http://localhost:8080/jerseyserver/test/postxml");
Invocation.Builder invocationBuilder = webTarget.request(MediaType.APPLICATION_XML);
RESTRequest request = new RESTRequest();
request.setType("test");
request.setParam("hello world");
Response response = invocationBuilder.post(Entity.entity(request, MediaType.APPLICATION_XML));
System.out.println(response.getStatus());
RESTResponse result = response.readEntity(RESTResponse.class);
System.out.println(result.getRespCode());
System.out.println(result.getRespDesc());
System.out.println(result.getResult());
}
private static void postJSONTest(){
Client client = ClientBuilder.newClient( new ClientConfig().register( LoggingFilter.class ) );
WebTarget webTarget = client.target("http://localhost:8080/jerseyserver/test/postjson");
Invocation.Builder invocationBuilder = webTarget.request(MediaType.APPLICATION_JSON);
RESTRequest request = new RESTRequest();
request.setType("test");
request.setParam("hello world");
Response response = invocationBuilder.post(Entity.entity(request, MediaType.APPLICATION_JSON));
System.out.println(response.getStatus());
RESTResponse result = response.readEntity(RESTResponse.class);
System.out.println(result.getRespCode());
System.out.println(result.getRespDesc());
System.out.println(result.getResult());
}
}
ApacheHttpClient
package apache;
import java.io.IOException;
import jersey.RESTRequest;
import jersey.RESTResponse;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
public class ApacheHttpClientPost {
public static void main(String[] args) {
postJson();
}
private static void postJson(){
try {
HttpClient httpClient = HttpClientBuilder.create().build();
HttpPost httpPost = new HttpPost(
"http://localhost:8080/jerseyserver/test/postjson");
httpPost.addHeader("Content-Type", "application/json");
// httpPost.addHeader("Accept", "text/plain");
RESTRequest request = new RESTRequest();
request.setType("test");
request.setParam("hello world");
String requestJsonString = new ObjectMapper().writeValueAsString(request);
StringEntity entity = new StringEntity(requestJsonString);
httpPost.setEntity(entity);
HttpResponse httpResponse = httpClient.execute(httpPost);
String responseJsonString = EntityUtils.toString(httpResponse.getEntity());
System.out.println(responseJsonString);
RESTResponse response = new ObjectMapper().readValue(responseJsonString, RESTResponse.class);
System.out.println(response.getRespCode());
System.out.println(response.getRespDesc());
System.out.println(response.getResult());
} catch (IOException e) {
e.printStackTrace();
}
}
}