本文是基于jersey的web service 的两个小例子,一个GET请求,一个POST请求
项目结构图如下:
build.gradle文件内容如下:
apply plugin: "java"
apply plugin: "idea"
idea {
module {
downloadSources = true
downloadJavadoc = true
}
}
repositories {
mavenCentral()
mavenLocal()
}
dependencies {
compile 'com.sun.jersey:jersey-core:1.19'
compile 'com.sun.jersey:jersey-server:1.19'
compile 'com.sun.jersey:jersey-client:1.19'
compile 'com.sun.jersey:jersey-json:1.19'
compile 'com.sun.jersey:jersey-bundle:1.19'
compile 'asm:asm:3.3.1'
}
HelloService.java代码如下:
package com.test.service;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
/**
* Created by yangjianzhou on 15-11-22.
*/
@Path("/test")
public class HelloService {
@GET
@Path("/hello")
@Produces(MediaType.APPLICATION_JSON)
public String hello(@QueryParam("name") String name) {
return "GET METHOD : " + name;
}
@POST
@Path("/greet")
@Produces(MediaType.APPLICATION_JSON)
public String greet(@FormParam("name") String name) {
return "POST METHOD : " + name;
}
}
TestHelloService.java代码如下:
package com.test.service;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.core.util.MultivaluedMapImpl;
import javax.ws.rs.core.MediaType;
import java.net.URI;
/**
* Created by yangjianzhou on 15-11-22.
*/
public class TestHelloService {
public static void main(String[] args) throws Exception{
testHello();
testGreet();
}
public static void testHello() throws Exception{
Client client = Client.create();
URI uri = new URI("http://localhost:8080/jerseyTest/service/test/hello?name=yangjianzhou");
WebResource resource = client.resource(uri);
String result = resource.get(String.class);
System.out.println(result);
}
public static void testGreet() throws Exception{
Client client = Client.create();
URI uri = new URI("http://localhost:8080/jerseyTest/service/test/greet");
WebResource resource = client.resource(uri);
MultivaluedMapImpl params = new MultivaluedMapImpl();
params.add("name" , "yangjianzhou");
String result = resource.queryParams(params).type(MediaType.APPLICATION_FORM_URLENCODED_TYPE).post(String.class);
System.out.println(result);
}
}
web.xml代码如下:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
<servlet>
<servlet-name>rest</servlet-name>
<servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>com.sun.jersey.config.property.package</param-name>
<param-value>com.test</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>rest</servlet-name>
<url-pattern>/service/*</url-pattern>
</servlet-mapping>
</web-app>
将应用jerseyTest部署到tomcat中,运行TestHelloService.java
输出结果如下: