Restful Web Services Interview
Restful Web Services Interview
Restful Web Services Interview
In the previous example we have seen how to read query paramters from the request using
@QueryParam annotation. What if the user request is in the below format? same id with multiple
values?
http://localhost:8080/RestfulWebServices/employee/query?id=1016&id=1017&id=1415
In the above URL, the id value is same, but with different values, this can be easily readable as a
list of values using UriInfo object.
In the previous examples we have given details of application setup, dependencies, web.xml file
configurations: If you want to know about these configuration, please refer these:
package com.javacofee.restful;
import java.util.List;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
@Path("/employee")
public class QueryParamExampleService {
@GET
@Path("/query")
public Response getEmployeeQuery(@Context UriInfo uriInfo){
In this page you can see an example to pass http header info as a method input using
@HeaderParam annotation.
In the previous examples we have given details of application setup, dependencies, web.xml file
configurations: If you want to know about these configuration, please refer these:
package com.javacoffee.restful;
import javax.ws.rs.GET;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.Path;
import javax.ws.rs.core.Response;
@Path("/http-header")
public class HttpHeaderService {
@GET
@Path("query")
public Response queryHeaderInfo(@HeaderParam("Cache-Control") String
ccControl,
@HeaderParam("User-Agent") String
uaStr){
Output:
Received http headers are Cache-Control: max-age=0
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_2) AppleWebKit/537.36
(KHTML, like Gecko)
Chrome/38.0.2125.104 Safari/537.36
In this page you can see an example to query http header info using @Context annotation and
HttpHeaders.
In the previous examples we have given details of application setup, dependencies, web.xml file
configurations: If you want to know about these configuration, please refer these:
package com.javacoffee.restful;
import java.util.Set;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.Response;
@Path("/http-header")
public class HttpHeaderService {
@GET
@Path("query")
public Response queryHeaderInfo(@Context HttpHeaders httpHeaders){
In this page you will see an example for how to upload a file using Jersey API in restful web
services.
In order to implement file upload feature, include jersey-multipart dependency in your pom.xml
file:
2 <project xmlns="http://maven.apache.org/POM/4.0.0"
3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
4 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
5 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
6
7 <groupId>RestfulWebServices</groupId>
8 <artifactId>RestfulWebServices</artifactId>
<version>0.0.1-SNAPSHOT</version>
9
<packaging>war</packaging>
10
<dependencies>
11
<dependency>
12
<groupId>com.sun.jersey</groupId>
13 <artifactId>jersey-server</artifactId>
14 <version>1.17</version>
15 </dependency>
16 <dependency>
17 <groupId>com.sun.jersey</groupId>
<artifactId>jersey-servlet</artifactId>
18
<version>1.17</version>
19
</dependency>
20
<dependency>
21
<groupId>com.sun.jersey.contribs</groupId>
22 <artifactId>jersey-multipart</artifactId>
23 <version>1.17</version>
24 </dependency>
25 </dependencies>
26</project>
27
28
2 xmlns="http://java.sun.com/xml/ns/j2ee"
3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
4 xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
5 http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
6
<servlet>
7
<servlet-name>jersey-serlvet</servlet-name>
8
<servlet-class>
9
com.sun.jersey.spi.container.servlet.ServletContainer
10
</servlet-class>
11 <init-param>
12 <param-name>jersey.config.server.provider.packages</param-
name>
13
<param-value>com.java2novice.restful</param-value>
14
</init-param>
15
<load-on-startup>1</load-on-startup>
16
</servlet>
17
18 <servlet-mapping>
19 <servlet-name>jersey-serlvet</servlet-name>
20 <url-pattern>/rest/*</url-pattern>
21 </servlet-mapping>
22</web-app>
23
?
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
1
"http://www.w3.org/TR/html4/loose.dtd">
2
<html>
3
<head>
4
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
5 <title>Upload File Example</title>
6 </head>
7 <body>
<h1>Upload File</h1>
8
<form action="rest/test/upload" method="post" enctype="multipart/form-
9 data">
12 </form>
13</body>
</html>
14
15
Here is the upload service class, we are using @FormDataParam annotation to receive uploaded
file and FormDataContentDisposition to receive file properties like name, header, etc.
?
package com.javacoffee.restful;
1
2
import java.io.File;
3
import java.io.FileOutputStream;
4
import java.io.IOException;
5 import java.io.InputStream;
6 import java.io.OutputStream;
8 import javax.ws.rs.Consumes;
9 import javax.ws.rs.POST;
10import javax.ws.rs.Path;
import javax.ws.rs.Produces;
11
import javax.ws.rs.core.MediaType;
12
import com.sun.jersey.core.header.FormDataContentDisposition;
13
import com.sun.jersey.multipart.FormDataParam;
14
15@Path("test")
17
private static final String FOLDER_PATH = "C:\my_files\";
18
19
@POST
20
@Path("/upload")
21
@Consumes(MediaType.MULTIPART_FORM_DATA)
22
@Produces(MediaType.TEXT_PLAIN)
23 public String uploadFile(@FormDataParam("file") InputStream fis,
24 @FormDataParam("file") FormDataContentDisposition fdcd)
{
25
26
OutputStream outpuStream = null;
27
String fileName = fdcd.getFileName();
28
System.out.println("File Name: " + fdcd.getFileName());
29
String filePath = FOLDER_PATH + fileName;
30
31 try {
32 int read = 0;
42 if(outpuStream != null){
43 try{outpuStream.close();} catch(Exception ex){}
44 }
}
45
return "File Upload Successfully !!";
46
}
47
}
48
49
50
51
52
http://localhost:8080/RestfulWebServices/index.html
Output
How to download file using java restful web
services?
You need to do two stpes to download a file from java restful web services.
1) Annotate your service method with @Produces annotation. This annotation should have the
file MIME type as a value. For example, if you are downloading pdf file then MIME type should
be "application/pdf", incase if you are downloading png image file, then MIME type should be
"image/png".
2) In the Response header, set “Content-Disposition” details, which helps to prompt download
box on browser.
In the previous examples we have given details of application setup, dependencies, web.xml file
configurations: If you want to know about these configuration, please refer these:
package com.java2novice.restful;
import java.io.File;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.ResponseBuilder;
@Path("/download")
public class RestDownloadService {
@GET
@Path("/service-record")
@Produces("application/pdf")
public Response getFile() {
http://localhost:8080/RestfulWebServices/download/service-record
In this page you will see support for XML using JAXB and RESTEasy API. JAXB is used for
mapping java classes to equivalent xml documents and vice versa. It is done using marshalling
and and unmarshalling features of JAXB. In this example we will convert Order object to xml
format.
We need resteasy-jaxb-provider.jar file to support xml file, here is the pom.xml file.
8 <version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
9
<repositories>
10
<repository>
11
<id>jboss</id>
12
<url>https://repository.jboss.org/nexus/content/groups/public-
13jboss/</url>
</repository>
14
</repositories>
15
<dependencies>
16
<dependency>
17
<groupId>org.jboss.resteasy</groupId>
18
<artifactId>resteasy-jaxb-provider</artifactId>
19 <version>2.3.7.Final</version>
20 </dependency>
21 <dependency>
22 <groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-jaxrs</artifactId>
23
<version>2.3.7.Final</version>
24
</dependency>
25
</dependencies>
26
</project>
27
28
29
2 xmlns="http://java.sun.com/xml/ns/j2ee"
3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
4 xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
5
6
<!-- Auto scan REST service -->
7
<context-param>
8
<param-name>resteasy.scan</param-name>
9
<param-value>true</param-value>
10 </context-param>
11
12 <listener>
13 <listener-class>
14 org.jboss.resteasy.plugins.server.servlet.ResteasyBootstrap
15 </listener-class>
</listener>
16
17
<servlet>
18
<servlet-name>resteasy-servlet</servlet-name>
19
<servlet-class>
20
org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher
21 </servlet-class>
22 </servlet>
23
24 <servlet-mapping>
25 <servlet-name>resteasy-servlet</servlet-name>
26 <url-pattern>/*</url-pattern>
</servlet-mapping>
27
</web-app>
28
29
30
Our model class Order is annotated with required JAXB annoations to support xml
transformation:
1 package com.javacoffee.model;
3 import javax.xml.bind.annotation.XmlAttribute;
4 import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
5
6
@XmlRootElement(name = "order")
7
public class Order {
8
10
private int orderNo;
11
private String custmer;
12 private String address;
13 private String amount;
14
15 @XmlAttribute(name = "order-no")
return orderNo;
17
}
18
public void setOrderNo(int orderNo) {
19
this.orderNo = orderNo;
20
}
21
22
@XmlElement
23 public String getCustmer() {
24 return custmer;
25 }
26 public void setCustmer(String custmer) {
27 this.custmer = custmer;
}
28
29
@XmlElement
30
public String getAddress() {
31
return address;
32
}
33 public void setAddress(String address) {
34 this.address = address;
35 }
36
37 @XmlElement(name = "bill-amount")
return amount;
39
}
40
public void setAmount(String amount) {
41
this.amount = amount;
42
}
43
44}
45
46
47
48
Note that our restful web service API returning xml, so annotate your service method with
@Produces and specify MIME type as application/xml.
?
package com.javacoffee.restful;
1
2 import javax.ws.rs.GET;
3 import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
4
import javax.ws.rs.Produces;
5
import com.java2novice.model.Order;
6
7
@Path("/order-inventory")
8
public class OrderInventoryService {
9
10 @GET
11 @Path("/order/{orderId}")
12 @Produces("application/xml")
14
ord.setOrderNo(orderId);
16
ord.setCustmer("Java2Novice");
17
ord.setAddress("Bangalore");
18
ord.setAmount("$2000");
19
return ord;
20 }
21}
22
23
24
http://localhost:8080/RestfulWebServices/order-inventory/order/1016
XML based Restful web service with Jersey
and JAXB.
In this page you will see support for XML using JAXB and Jersey API. JAXB is used for
mapping java classes to equivalent xml documents and vice versa. It is done using marshalling
and and unmarshalling features of JAXB. In this example we will convert Order object to xml
format.
9 <packaging>war</packaging>
<dependencies>
10
<dependency>
11
<groupId>com.sun.jersey</groupId>
12
<artifactId>jersey-server</artifactId>
13
<version>1.17</version>
14 </dependency>
15 <dependency>
16 <groupId>com.sun.jersey</groupId>
17 <artifactId>jersey-servlet</artifactId>
18 <version>1.17</version>
</dependency>
19
</dependencies>
20
</project>
21
22
23
?
<web-app id="WebApp_ID" version="2.4"
1
xmlns="http://java.sun.com/xml/ns/j2ee"
2
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
3
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
4
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
5 <servlet>
6 <servlet-name>jersey-serlvet</servlet-name>
7 <servlet-
class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
8
<init-param>
9
<param-name>jersey.config.server.provider.packages</param-name>
10 <param-value>com.java2novice.restful</param-value>
11 </init-param>
<load-on-startup>1</load-on-startup>
12
</servlet>
13
<servlet-mapping>
14
<servlet-name>jersey-serlvet</servlet-name>
15
<url-pattern>/*</url-pattern>
16 </servlet-mapping>
17</web-app>
18
19
Our model class Order is annotated with required JAXB annoations to support xml
transformation:
?
package com.javacoffee.model;
1
2
import javax.xml.bind.annotation.XmlAttribute;
3
import javax.xml.bind.annotation.XmlElement;
4 import javax.xml.bind.annotation.XmlRootElement;
6 @XmlRootElement(name = "order")
14
@XmlAttribute(name = "order-no")
15 public int getOrderNo() {
16 return orderNo;
}
17
public void setOrderNo(int orderNo) {
18
this.orderNo = orderNo;
19
}
20
21
@XmlElement
22 public String getCustmer() {
23 return custmer;
24 }
26 this.custmer = custmer;
}
27
28
@XmlElement
29
public String getAddress() {
30
return address;
31
}
32 public void setAddress(String address) {
33 this.address = address;
34 }
35
36 @XmlElement(name = "bill-amount")
return amount;
38
}
39
public void setAmount(String amount) {
40
this.amount = amount;
41
}
42
43}
44
45
46
47
48
Note that our restful web service API returning xml, so annotate your service method with
@Produces and specify MIME type as application/xml.
?
package com.javacoffee.restful;
1
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;
8 import com.java2novice.model.Order;
10@Path("/order-inventory")
12
@GET
13
@Path("/order/{orderId}")
14
@Produces(MediaType.APPLICATION_XML)
15
public Order getUserById(@PathParam("orderId") Integer orderId){
16
17
Order ord = new Order();
18
ord.setOrderNo(orderId);
19 ord.setCustmer("Java2Novice");
20 ord.setAddress("Bangalore");
ord.setAmount("$2000");
21
return ord;
22
}
23
}
24
25
26
http://localhost:8080/RestfulWebServices/order-inventory/order/1016
In this page you will see support for Json using RESTEasy and Jackson APIs. Jackson is is a
multi-purpose Java library for processing JSON data format. Jackson aims to be the best possible
combination of fast, correct, lightweight, and ergonomic for developers In this example we will
convert Order object to json format.
Here is the pom.xml file.
2 <project xmlns="http://maven.apache.org/POM/4.0.0"
3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
4
http://maven.apache.org/xsd/maven-4.0.0.xsd">
5
<modelVersion>4.0.0</modelVersion>
6
<groupId>RestfulWebServices</groupId>
7
<artifactId>RestfulWebServices</artifactId>
8
<version>0.0.1-SNAPSHOT</version>
9 <packaging>war</packaging>
10 <repositories>
11 <repository>
12 <id>jboss</id>
<url>https://repository.jboss.org/nexus/content/groups/public-
13
jboss/</url>
14 </repository>
15 </repositories>
16 <dependencies>
17 <dependency>
18 <groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-jackson-provider</artifactId>
19
<version>2.3.7.Final</version>
20
</dependency>
21
<dependency>
22
<groupId>org.jboss.resteasy</groupId>
23 <artifactId>resteasy-jaxrs</artifactId>
24 <version>2.3.7.Final</version>
25 </dependency>
26 </dependencies>
27</project>
28
29
2 xmlns="http://java.sun.com/xml/ns/j2ee"
3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
4
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
5
6
<!-- Auto scan REST service -->
7
<context-param>
8
<param-name>resteasy.scan</param-name>
9
<param-value>true</param-value>
10 </context-param>
11 <listener>
12 <listener-class>
13 org.jboss.resteasy.plugins.server.servlet.ResteasyBootstrap
</listener-class>
14
</listener>
15
<servlet>
16
<servlet-name>resteasy-servlet</servlet-name>
17
<servlet-class>
18
org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher
19 </servlet-class>
20 </servlet>
21 <servlet-mapping>
22 <servlet-name>resteasy-servlet</servlet-name>
23 <url-pattern>/*</url-pattern>
24 </servlet-mapping>
</web-app>
25
26
27
Our model class Order is annotated with required jackson annoations to support json
transformation:
?
package com.javacoffee.model;
1
2
import org.codehaus.jackson.annotate.JsonProperty;
3
4
public class Order {
5
6
@JsonProperty("order-no")
7 private int orderNo;
8
9 @JsonProperty
11
13
@JsonProperty("bill-amount")
14
private String amount;
15
16
17
public int getOrderNo() {
18
return orderNo;
19
}
20 public void setOrderNo(int orderNo) {
21 this.orderNo = orderNo;
}
22
23
public String getCustmer() {
24
return custmer;
25
}
26
public void setCustmer(String custmer) {
27 this.custmer = custmer;
28 }
29
31 return address;
32 }
36
public String getAmount() {
37
return amount;
38 }
39 public void setAmount(String amount) {
40 this.amount = amount;
41 }
42
43}
44
45
46
47
Remember that our restful web service API returning json, so annotate your service method with
@Produces and specify MIME type as application/jon.
1
package com.javacoffee.restful;
2
3
import javax.ws.rs.GET;
4
import javax.ws.rs.Path;
5 import javax.ws.rs.PathParam;
6 import javax.ws.rs.Produces;
7 import javax.ws.rs.core.MediaType;
9 import com.java2novice.model.Order;
10
11@Path("/order-inventory")
public class OrderInventoryService {
12
13
@GET
14
@Path("/order/{orderId}")
15
@Produces(MediaType.APPLICATION_JSON)
16
public Order getUserById(@PathParam("orderId") Integer orderId){
17
20 ord.setCustmer("Java2Novice");
21 ord.setAddress("Bangalore");
ord.setAmount("$2000");
22
return ord;
23
}
24
}
25
26
http://localhost:8080/RestfulWebServices/order-inventory/order/1016
In this page you will see support for Json using Jersey and Jackson APIs. Jackson is is a multi-
purpose Java library for processing JSON data format. Jackson aims to be the best possible
combination of fast, correct, lightweight, and ergonomic for developers In this example we will
convert Order object to json format.
?
<?xml version="1.0" encoding="UTF-8"?>
1
<project xmlns="http://maven.apache.org/POM/4.0.0"
2
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
3
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
4
http://maven.apache.org/xsd/maven-4.0.0.xsd">
5 <modelVersion>4.0.0</modelVersion>
6 <groupId>RestfulWebServices</groupId>
<artifactId>RestfulWebServices</artifactId>
7
<version>0.0.1-SNAPSHOT</version>
8
<packaging>war</packaging>
9
<dependencies>
10
<dependency>
11 <groupId>com.sun.jersey</groupId>
12 <artifactId>jersey-server</artifactId>
13 <version>1.17</version>
14 </dependency>
15 <dependency>
<groupId>com.sun.jersey</groupId>
16
<artifactId>jersey-servlet</artifactId>
17
<version>1.17</version>
18
</dependency>
19
<dependency>
20 <groupId>com.sun.jersey</groupId>
21 <artifactId>jersey-json</artifactId>
22 <version>1.17</version>
23 </dependency>
24 </dependencies>
</project>
25
26
27
28
?
1
3 xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
4
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
5
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
6
7
<servlet>
8
<servlet-name>jersey-serlvet</servlet-name>
9 <servlet-class>
10 com.sun.jersey.spi.container.servlet.ServletContainer
11 </servlet-class>
12 <init-param>
13 <param-name>jersey.config.server.provider.packages</param-name>
<param-value>com.java2novice.restful</param-value>
14
</init-param>
15
<init-param>
16
<param-name>com.sun.jersey.api.json.POJOMappingFeature</param-
17name>
18 <param-value>true</param-value>
</init-param>
19
<load-on-startup>1</load-on-startup>
20
</servlet>
21
<servlet-mapping>
22
<servlet-name>jersey-serlvet</servlet-name>
23 <url-pattern>/*</url-pattern>
24 </servlet-mapping>
25</web-app>
26
Our model class Order is annotated with required jackson annoations to support json
transformation:
?
1 package com.javacoffee.model;
3 import org.codehaus.jackson.annotate.JsonProperty;
4
public class Order {
5
6
@JsonProperty("order-no")
7
private int orderNo;
8
9
@JsonProperty
10
private String custmer;
11
14 @JsonProperty("bill-amount")
15 private String amount;
16
17
19 return orderNo;
}
20
public void setOrderNo(int orderNo) {
21
this.orderNo = orderNo;
22
}
23
24
public String getCustmer() {
25 return custmer;
26 }
27 public void setCustmer(String custmer) {
28 this.custmer = custmer;
29 }
30
public String getAddress() {
31
return address;
32
}
33
public void setAddress(String address) {
34
this.address = address;
35 }
36
39 }
this.amount = amount;
41
}
42
43
}
44
45
46
47
Remember that our restful web service API returning json, so annotate your service method with
@Produces and specify MIME type as application/jon.
?
package com.javacoffee.restful;
1
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
import com.java2novice.model.Order;
8
9
@Path("/order-inventory")
10
public class OrderInventoryService {
11
12
@GET
13
@Path("/order/{orderId}")
14 @Produces(MediaType.APPLICATION_JSON)
15 public Order getUserById(@PathParam("orderId") Integer orderId){
16
18 ord.setOrderNo(orderId);
19 ord.setCustmer("Java2Novice");
ord.setAddress("Bangalore");
20
ord.setAmount("$2000");
21
return ord;
22
}
23
}
24
25
26
http://localhost:8080/RestfulWebServices/order-inventory/order/1016
How to input json request with Jersey and
Jackson?
In this page you will see support for Json using Jersey and Jackson APIs. Jackson is is a multi-
purpose Java library for processing JSON data format. Jackson aims to be the best possible
combination of fast, correct, lightweight, and ergonomic for developers In this example we will
send json as a input, and the json request will be mapped to Order object.
2 <project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
3
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
4
http://maven.apache.org/xsd/maven-4.0.0.xsd">
5
<modelVersion>4.0.0</modelVersion>
6
<groupId>RestfulWebServices</groupId>
7
<artifactId>RestfulWebServices</artifactId>
8 <version>0.0.1-SNAPSHOT</version>
9 <packaging>war</packaging>
10 <dependencies>
11 <dependency>
12 <groupId>com.sun.jersey</groupId>
<artifactId>jersey-server</artifactId>
13
<version>1.17</version>
14
</dependency>
15
<dependency>
16
<groupId>com.sun.jersey</groupId>
17 <artifactId>jersey-servlet</artifactId>
18 <version>1.17</version>
19 </dependency>
20 <dependency>
21 <groupId>com.sun.jersey</groupId>
<artifactId>jersey-json</artifactId>
22
<version>1.17</version>
23
</dependency>
24
</dependencies>
25
</project>
26
27
28
2 xmlns="http://java.sun.com/xml/ns/j2ee"
3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
4 xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
5
6
7 <servlet>
8 <servlet-name>jersey-serlvet</servlet-name>
<servlet-class>
9
com.sun.jersey.spi.container.servlet.ServletContainer
10
</servlet-class>
11
<init-param>
12
<param-name>jersey.config.server.provider.packages</param-
13name>
<param-value>com.java2novice.restful</param-value>
14
</init-param>
15
<init-param>
16
<param-name>com.sun.jersey.api.json.POJOMappingFeature</param-
17name>
18 <param-value>true</param-value>
19 </init-param>
<load-on-startup>1</load-on-startup>
20
</servlet>
21
<servlet-mapping>
22
<servlet-name>jersey-serlvet</servlet-name>
23
<url-pattern>/*</url-pattern>
24 </servlet-mapping>
25</web-app>
26
Our model class Order is annotated with required jackson annoations to support json
transformation:
?
package com.javacoffee.model;
1
2
import org.codehaus.jackson.annotate.JsonProperty;
3
4
public class Order {
5
6 @JsonProperty
8
private String address;
9
10
@JsonProperty("bill-amount")
11
private String amount;
12
13
public String getCustmer() {
14
return custmer;
15 }
16 public void setCustmer(String custmer) {
17 this.custmer = custmer;
18 }
19
return address;
21
}
22
public void setAddress(String address) {
23
this.address = address;
24
}
25
30 this.amount = amount;
}
31
32
33}
34
35
36
Remember that our restful web service API accepting json as an input, we should annotate our
service method with @Consumes and specify MIME type as application/jon. Closely watch our
service method input parameter, it is of type Order, before calling our service method, the json
is mapped to Order object.
1 package com.javacoffee.restful;
3 import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
4
import javax.ws.rs.Path;
5
import javax.ws.rs.Produces;
6
import javax.ws.rs.core.MediaType;
7
import javax.ws.rs.core.Response;
8
9 import com.javacoffee.model.Order;
10
11 @POST
12 @Path("/order")
13 @Consumes(MediaType.APPLICATION_JSON)
15
System.out.println("Received order from
16:"+inputOrder.getCustmer());
19
20 return Response.status(200).entity("Your order is in-
progress").build();
21
}
22
}
23
Output:
1 package com.javacoffee.rest.client;
3 import java.io.BufferedReader;
4 import java.io.IOException;
5 import java.io.InputStream;
import java.io.InputStreamReader;
6
import java.net.HttpURLConnection;
7
import java.net.MalformedURLException;
8
import java.net.URL;
9
10
public class RestJavaNetClient {
11
21 urlConn.setConnectTimeout(5000);
22 urlConn.setReadTimeout(5000);
23 urlConn.setRequestProperty("Accept", "application/json");
24 if (urlConn.getResponseCode() != HttpURLConnection.HTTP_OK) {
return;
26
}
27
System.out.println("Connected to the server...");
28
InputStream is = urlConn.getInputStream();
29
reader = new BufferedReader(new InputStreamReader((is)));
30 System.out.println("Reading data from server...");
31 String tmpStr = null;
33 System.out.println(tmpStr);
34 }
} catch (MalformedURLException e) {
35
// TODO Auto-generated catch block
36
e.printStackTrace();
37
} catch (IOException e) {
38
// TODO Auto-generated catch block
39 e.printStackTrace();
40 } finally {
41 try {
} catch(Exception ex){
44
45
}
46
}
47
}
48
}
49
50
51
52
Output:
In this example you will see how to send json input through java client using POST method:
1 package com.javacoffee.rest.client;
3 import java.io.BufferedReader;
import java.io.IOException;
4
import java.io.InputStream;
5
import java.io.InputStreamReader;
6
import java.io.OutputStream;
7
import java.net.HttpURLConnection;
8 import java.net.MalformedURLException;
9 import java.net.URL;
10
12
14
24 urlConn.setDoOutput(true);
25 urlConn.setRequestMethod("POST");
urlConn.setRequestProperty("Content-Type", "application/json");
26
urlConn.setConnectTimeout(5000);
27
urlConn.setReadTimeout(5000);
28
urlConn.setRequestProperty("Accept", "application/json");
29
// send json input request
30
ouputStream = urlConn.getOutputStream();
31 ouputStream.write(jsonInput.getBytes());
32 ouputStream.flush();
33 if (urlConn.getResponseCode() != HttpURLConnection.HTTP_OK) {
return;
35
}
36
System.out.println("Connected to the server...");
37
InputStream is = urlConn.getInputStream();
38
reader = new BufferedReader(new InputStreamReader((is)));
39
String tmpStr = null;
40 while((tmpStr = reader.readLine()) != null){
41 System.out.println(tmpStr);
42 }
43 } catch (MalformedURLException e) {
48 } finally {
try {
49
if(reader != null) reader.close();
50
if(urlConn != null) urlConn.disconnect();
51
} catch(Exception ex){
52
53
}
54 }
55 }
56}
57
58
59
60
61
Output:
In this page you will come to know how to create java client for restful web services using Jersey
API. You will see two sections here, the first section talks about how to connect to "GET"
request, and the second section shows how to connect to "POST" type of requests.
Java Client for GET Request using Jersey API
?
3 package com.javacoffee.rest.client;
5 import com.sun.jersey.api.client.Client;
6 import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
7
8
public class JersyGetClient {
9
1
0 public static void main(String a[]){
1
1 String url = "http://localhost:8080/RestfulWebServices/order-
inventory/order/1016";
1
2 Client restClient = Client.create();
1 .get(ClientResponse.cla
4 ss);
if(resp.getStatus() != 200){
1
5 System.err.println("Unable to connect to the server");
1 }
6 String output = resp.getEntity(String.class);
1 System.out.println("response: "+output);
7
}
1 }
8
1
9
2
0
2
1
2
2
Output:
response: {"custmer":"Java2Novice","address":"Bangalore","bill-
amount":"$2000"}
In this example you will see how to send json input through java client using POST method:
1 package com.javacoffee.rest.client;
3 import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
4
import com.sun.jersey.api.client.WebResource;
5
6
public class JerseyPostClient {
7
8
public static void main(String a[]){
9
10
String url = "http://localhost:8080/RestfulWebServices/order-
11inventory/order";
String jsonInput =
12
"{\"custmer\":\"Java2novice\",\"address\":\"Bangalore\","+
13 "\"bill-amount\":\"$2000\"}";
14 Client restClient = Client.create();
15 WebResource webResource = restClient.resource(url);
.post(ClientResponse.class, jsonInput);
17
if(resp.getStatus() != 200){
18
System.err.println("Unable to connect to the server");
19
}
20
String output = resp.getEntity(String.class);
21 System.out.println("response: "+output);
22 }
23}
24
Output:
1 package com.javacoffee.restful;
2
3 import java.io.IOException;
5 import javax.ws.rs.GET;
import javax.ws.rs.HeaderParam;
6
import javax.ws.rs.Path;
7
import javax.ws.rs.PathParam;
8
import javax.ws.rs.Produces;
9
import javax.ws.rs.core.MediaType;
10import sun.misc.BASE64Decoder;
11
12import com.java2novice.model.Order;
13
14@Path("/order-inventory")
16
17 @GET
@Path("/order/{orderId}")
18
@Produces(MediaType.APPLICATION_JSON)
19
public Object getUserById(@PathParam("orderId") Integer orderId,
20
@HeaderParam("authorization") String
21authString){
22
23 if(!isUserAuthenticated(authString)){
31
33
String decodedAuth = "";
34
// Header is in the format "Basic 5tyc0uiDat4"
35
// We need to extract data before decoding it back to original
36string
47 System.out.println(decodedAuth);
48
/**
49
* here you include your logic to validate user authentication.
50
* it can be using ldap, or token exchange mechanism or your
51
* custom authentication mechanism.
52
*/
53
// your validation code goes here....
54
55 return true;
56 }
57}
58
59
60
61
Java Client for GET Request using Jersey API with HTTP basic authentication
?
1 package com.javacoffee.rest.client;
3 import sun.misc.BASE64Encoder;
5 import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
6
import com.sun.jersey.api.client.WebResource;
7
8
public class JersyGetClient {
9
10
public static void main(String a[]){
11
12
String url = "http://localhost:8080/RestfulWebServices/order-
13inventory/order/1016";
24 if(resp.getStatus() != 200){
30