You are on page 1of 51

How to read multiple values of a query

paramter in JAX-RS restful web services?

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){

/** read complete employee id list from request query parameter**/


List<String> empIdList = uriInfo.getQueryParameters().get("id");
System.out.println("Received List: "+empIdList);
/** read first employee id from request query parameter **/
String firstEmpId = uriInfo.getQueryParameters().getFirst("id");
System.out.println("First emp record from the request: "+firstEmpId);

return Response.status(200).entity("processed request").build();


}
}

In the above example, if you use "/employee/query?id=1016&id=1017&id=1415" URI pattern


with query parameters, here is the output:
Output:
INFO [stdout] (http--127.0.0.1-8080-1) Received List: [1016, 1017, 1415]
INFO [stdout] (http--127.0.0.1-8080-1) First emp record from the request:
1016

How to pass header parameters as method


inputs in JAX-RS restful web services?

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){

String resp = "Received http headers are Cache-Control: "+ccControl+


"<br>User-Agent: "+uaStr;
return Response.status(200).entity(resp).build();
}
}

In the above example, if you use "http://localhost:8080/RestfulWebServices/http-


header/query" URI pattern, here is the output:

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

How to read header parameters in JAX-RS


restful web services?

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){

/** how to get specific header info? **/


String cacheControl = httpHeaders.getRequestHeader("Cache-
Control").get(0);
System.out.println("Cache-Control: "+cacheControl);
/** get list of all header parameters from request **/
Set<String> headerKeys = httpHeaders.getRequestHeaders().keySet();
for(String header:headerKeys){
System.out.println(header+":"+httpHeaders.getRequestHeader(heade
r).get(0));
}
return Response.status(200).entity("successfully queried header
info").build();
}
}
Test with "http://localhost:8080/RestfulWebServices/http-header/query" URL, here is the
output:
Output:
Cache-Control: max-age=0
[stdout] (http--127.0.0.1-8080-1) host:localhost:8080
[stdout] (http--127.0.0.1-8080-1) connection:keep-alive
[stdout] (http--127.0.0.1-8080-1) cache-control:max-age=0
[stdout] (http--127.0.0.1-8080-1)
accept:text/html,application/xhtml+xml,application/xml;q=0.9,
image/webp,*/*;q=0.8
[stdout] (http--127.0.0.1-8080-1) 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
[stdout] (http--127.0.0.1-8080-1) accept-encoding:gzip,deflate,sdch
[stdout] (http--127.0.0.1-8080-1) accept-language:en-US,en;q=0.8
[stdout] (http--127.0.0.1-8080-1)
cookie:__atuvc=24%7C23%2C0%7C24%2C3%7C25%2C45%7C26%2C41%7C27;
bsau=14136427273262128776

How to upload file using Jersey restful web


services?

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:

1 <?xml version="1.0" encoding="UTF-8"?>

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

web.xml file reference:

1 <web-app id="WebApp_ID" version="2.4"

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

Here is the HTML upload form:

?
<!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">

10 <p>Select a file : <input type="file" name="file"/></p>

11 <input type="submit" value="Upload File" />

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")

16public class RestUploadService {

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;

33 byte[] bytes = new byte[1024];

34 outpuStream = new FileOutputStream(new File(filePath));

while ((read = fis.read(bytes)) != -1) {


35
outpuStream.write(bytes, 0, read);
36
}
37
outpuStream.flush();
38
outpuStream.close();
39
} catch(IOException iox){
40 iox.printStackTrace();
41 } finally {

42 if(outpuStream != null){
43 try{outpuStream.close();} catch(Exception ex){}

44 }

}
45
return "File Upload Successfully !!";
46
}
47
}
48

49

50

51

52

Try below URL to upload file:

http://localhost:8080/RestfulWebServices/index.html

User Upload Form

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() {

File file = new File("C:\java2novice\employee_1415.pdf");

ResponseBuilder response = Response.ok((Object) file);


response.header("Content-Disposition",
"attachment; filename=\"employee_1415.pdf\"");
return response.build();
}
}

Try below URL to download file:

http://localhost:8080/RestfulWebServices/download/service-record

XML based Restful web service with


RESTEasy and JAXB.

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.

1 <?xml version="1.0" encoding="UTF-8"?>


<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>
7 <artifactId>RestfulWebServices</artifactId>

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

Web.xml file for your reference:

1 <web-app id="WebApp_ID" version="2.4"

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")

16 public int getOrderNo() {

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")

38 public String getAmount() {

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")

13 public Order getUserById(@PathParam("orderId") Integer orderId){

14

15 Order ord = new Order();

ord.setOrderNo(orderId);
16
ord.setCustmer("Java2Novice");
17
ord.setAddress("Bangalore");
18
ord.setAmount("$2000");
19
return ord;
20 }
21}

22

23

24

Try below URL to get xml output:

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.

Here is the pom.xml file.

1 <?xml version="1.0" encoding="UTF-8"?>


<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>
7 <artifactId>RestfulWebServices</artifactId>
8 <version>0.0.1-SNAPSHOT</version>

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.xml file for your reference:

?
<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")

7 public class Order {

10 private int orderNo;

private String custmer;


11
private String address;
12
private String amount;
13

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 }

25 public void setCustmer(String custmer) {

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")

37 public String getAmount() {

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")

11public class OrderInventoryService {

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

Try below URL to get xml output:

http://localhost:8080/RestfulWebServices/order-inventory/order/1016

Json based Restful web service with


RESTEasy and Jackson.

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.

1 <?xml version="1.0" encoding="UTF-8"?>

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

Web.xml file for your reference:

1 <web-app id="WebApp_ID" version="2.4"

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

10 private String custmer;

11

12 private String address;

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

30 public String getAddress() {

31 return address;

32 }

public void setAddress(String address) {


33
this.address = address;
34
}
35

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

18 Order ord = new Order();


19 ord.setOrderNo(orderId);

20 ord.setCustmer("Java2Novice");

21 ord.setAddress("Bangalore");

ord.setAmount("$2000");
22
return ord;
23
}
24
}
25
26

Try below URL to get xml output:

http://localhost:8080/RestfulWebServices/order-inventory/order/1016

son based Restful web service 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
convert Order object to json format.

Here is the pom.xml file. You need jersey-json jar file.

?
<?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

Web.xml file for your reference. In web.xml add


“com.sun.jersey.api.json.POJOMappingFeature” as “init-param” which supports Json object
mapping.

?
1

2 <web-app id="WebApp_ID" version="2.4"

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

12 private String address;


13

14 @JsonProperty("bill-amount")
15 private String amount;

16

17

18 public int getOrderNo() {

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

37 public String getAmount() {


38 return amount;

39 }

40 public void setAmount(String amount) {

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

17 Order ord = new Order();

18 ord.setOrderNo(orderId);

19 ord.setCustmer("Java2Novice");

ord.setAddress("Bangalore");
20
ord.setAmount("$2000");
21
return ord;
22
}
23
}
24

25

26

Try below URL to get xml output:

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.

Here is the pom.xml file. You need jersey-json jar file.

1 <?xml version="1.0" encoding="UTF-8"?>

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

Web.xml file for your reference. In web.xml add


“com.sun.jersey.api.json.POJOMappingFeature” as “init-param” which supports Json object
mapping.

1 <web-app id="WebApp_ID" version="2.4"

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

7 private String custmer;

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

20 public String getAddress() {

return address;
21
}
22
public void setAddress(String address) {
23
this.address = address;
24
}
25

26 public String getAmount() {


27 return amount;
28 }

29 public void setAmount(String amount) {

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)

14 public Response getUserById(Order inputOrder){

15
System.out.println("Received order from
16:"+inputOrder.getCustmer());

17 System.out.println("Order worth: "+inputOrder.getAmount());


18 System.out.println("Customer address: "+inputOrder.getAddress());

19
20 return Response.status(200).entity("Your order is in-
progress").build();
21
}
22
}
23

Here is the json requst and response:

The console output:

Output:

[stdout] (http--127.0.0.1-8080-1) Received order from :Java2Novice


[stdout] (http--127.0.0.1-8080-1) Order worth: $2000
[stdout] (http--127.0.0.1-8080-1) Customer address: Bangalore

Java client for restful web service using


java.net package
In this page you will come to know how to create java client for restful web services using
java.net package. We will have 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


?

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

12 public static void main(String a[]){


13

14 String url = "http://localhost:8080/RestfulWebServices/order-


inventory/order/1016";
15
HttpURLConnection urlConn = null;
16
BufferedReader reader = null;
17
try {
18
URL urlObj = new URL(url);
19 urlConn = (HttpURLConnection) urlObj.openConnection();
20 urlConn.setRequestMethod("GET");

21 urlConn.setConnectTimeout(5000);

22 urlConn.setReadTimeout(5000);

23 urlConn.setRequestProperty("Accept", "application/json");
24 if (urlConn.getResponseCode() != HttpURLConnection.HTTP_OK) {

25 System.err.println("Unable to connect to the URL...");

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;

32 while((tmpStr = reader.readLine()) != 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 {

42 if(reader != null) reader.close();

43 if(urlConn != null) urlConn.disconnect();

} catch(Exception ex){
44

45
}
46
}
47
}
48
}
49

50

51
52

The output for above code is:

Output:

Connected to the server...


Reading data from server...
{"custmer":"Java2Novice","address":"Bangalore","bill-amount":"$2000"}
Java Client for POST Request

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

11public class PostJavaNetClient {

12

13 public static void main(String a[]){

14

15 String url = "http://localhost:8080/RestfulWebServices/order-


inventory/order";
16 HttpURLConnection urlConn = null;
17 BufferedReader reader = null;
18 OutputStream ouputStream = null;
19 String jsonInput =
"{\"custmer\":\"Java2novice\",\"address\":\"Bangalore\","+
20
"\"bill-amount\":\"$2000\"}";
21
try {
22 URL urlObj = new URL(url);
23 urlConn = (HttpURLConnection) urlObj.openConnection();

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) {

34 System.err.println("Unable to connect to the URL...");

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) {

// TODO Auto-generated catch block


44
e.printStackTrace();
45
} catch (IOException e) {
46
// TODO Auto-generated catch block
47 e.printStackTrace();

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

The output for above code is:

Output:

Connected to the server...


Your order is in-progress

Java client for restful web service using


Jersey API

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 WebResource webResource = restClient.resource(url);


3 ClientResponse resp = webResource.accept("application/json")

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

The output for above code is:

Output:

response: {"custmer":"Java2Novice","address":"Bangalore","bill-
amount":"$2000"}

Java Client for POST Request using Jersey API

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);

16 ClientResponse resp = webResource.type("application/json")

.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

The output for above code is:

Output:

response: Your order is in-progress

Java restful webservices with HTTP basic authentication.

In the context of a HTTP transaction, basic access authentication is a method


for an HTTP user agent to provide a user name and password when making a
request.
HTTP Basic authentication implementation is the simplest technique for
enforcing access controls to web resources because it doesn't require
cookies, session identifier and login pages. Rather, HTTP Basic
authentication uses static, standard HTTP headers which means that no
handshakes have to be done in anticipation.
When the user agent wants to send the server authentication credentials it
may use the Authorization header. The Authorization header is constructed as
follows:
1) Username and password are combined into a string "username:password"
2) The resulting string is then encoded using Base64 encoding
3) The authorization method and a space i.e. "Basic " is then put before the
encoded string.
For example, if the user agent uses 'Aladdin' as the username and 'open
sesame' as the password then the header is formed as follows:
Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==
Java Rest Service method with GET Request which supports HTTP basic
authentication
?

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")

15public class OrderInventoryService {

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)){

return "{\"error\":\"User not authenticated\"}";


24
}
25
Order ord = new Order();
26
ord.setCustmer("Java2Novice");
27
ord.setAddress("Bangalore");
28
ord.setAmount("$2000");
29 return ord;
30 }

31

32 private boolean isUserAuthenticated(String authString){

33
String decodedAuth = "";
34
// Header is in the format "Basic 5tyc0uiDat4"
35
// We need to extract data before decoding it back to original
36string

37 String[] authParts = authString.split("\\s+");

38 String authInfo = authParts[1];

// Decode the data back to original string


39
byte[] bytes = null;
40
try {
41
bytes = new BASE64Decoder().decodeBuffer(authInfo);
42
} catch (IOException e) {
43
// TODO Auto-generated catch block
44 e.printStackTrace();
45 }

46 decodedAuth = new String(bytes);

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";

String name = "java2novice";


14
String password = "Simple4u!";
15
String authString = name + ":" + password;
16
String authStringEnc = new
17BASE64Encoder().encode(authString.getBytes());

18 System.out.println("Base64 encoded auth string: " + authStringEnc);

Client restClient = Client.create();


19
WebResource webResource = restClient.resource(url);
20
ClientResponse resp = webResource.accept("application/json")
21
.header("Authorization", "Basic "
22+ authStringEnc)
23 .get(ClientResponse.class);

24 if(resp.getStatus() != 200){

System.err.println("Unable to connect to the server");


25
}
26
String output = resp.getEntity(String.class);
27
System.out.println("response: "+output);
28
}
29}

30

You might also like