Download file using REST webservice

In this tutorial I am going to show you how we can download file using REST or RESTful web service.

The most important concept in REST is resources, which are identified by global IDs — typically using URIs. Client applications use HTTP methods (GET/ POST/ PUT/ DELETE) to manipulate the resource or collection of resources. A RESTful Web service is implemented using HTTP and the principles of REST. Typically, a RESTful Web service should define the following aspects:

The base/root URI for the Web service such as http://<host>/<appcontext/contextpath>/<url pattern>/<resources>.
The MIME type of the response data supported, which are JSON/XML/TEXT/HTML etc.
The set of operations supported by the service. (for example, POST, GET, PUT or DELETE).

Eclipse, JDK 1.8, JAX-RS jars 2.23.2
Have maven installed and configured
JAX-RS dependencies in pom.xml

For this tutorial we will create a web maven project in Eclipse. If you already have an idea on how to create a maven project in Eclipse will be great otherwise I will tell you here how to create a maven project in Eclipse.

Step 1. Create a web maven project in Eclipse

Go to File -> New -> Other. On popup window under Maven select Maven Project. Then click on Next. Select the workspace location – either default or browse the location. Click on Next. Now in next window select the row as highlighted from the below list of archtypes and click on Next button.

Now enter the required fields (Group Id, Artifact Id) as shown below
Group Id : com.roytuts
Artifact Id : rest
Step 2. Modify the pom.xml file as shown below.

<project xmlns="" xmlns:xsi=""
	<name>rest Maven Webapp</name>

Step 3. If you see JRE System Library[J2SE-1.5] then change the version by below process

Do right-click on the project and go to Build -> Configure build path, under Libraries tab click on JRE System Library[J2SE-1.5], click on Edit button and select the appropriate jdk 1.8 from the next window. Click on Finish then Ok.

Step 4. Modify web.xml file to use the jersey servlet

 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "" >
	<display-name>REST Service</display-name>
	<!-- Map /rest/* to Jersey -->

Step 5. Create a REST resource class as shown below

public class RestService {
	private static final String FILE_PATH = "D:/Documents/JavaJ2EE.doc";
	public Response getFile() {
		File file = new File(FILE_PATH);
		ResponseBuilder response = Response.ok((Object) file);
		response.header("Content-Disposition", "attachment; filename="" + file.getName() + """);

Step 6. Now run the application on Tomcat 8, you will see below output in the browser. Now you can either save the file or open the file.

REST webservice file download
Thanks for reading.

Leave a Reply

Your email address will not be published. Required fields are marked *