This is just a simple example. The focus is on using StreamingOutput API.
Below is the sample source for providing zip file from http request.
package com.test;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URL;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.StreamingOutput;
import org.apache.commons.io.IOUtils;
@Path("/zipfileservice/")
public class ZipService {
@GET
@Path("/helloWorld/{caller}/")
@Produces("application/text")
public String helloWorld(String caller) throws Exception{
return "Hello";
}
@GET
@Path("/helloWorldZip/{caller}/")
@Produces("application/zip")
public StreamingOutput helloWorldZip(String caller) throws Exception{
return new StreamingOutput(){
@Override
public void write(OutputStream arg0) throws IOException, WebApplicationException {
// TODO Auto-generated method stub
BufferedOutputStream bus = new BufferedOutputStream(arg0);
try {
//ByteArrayInputStream reader = (ByteArrayInputStream) Thread.currentThread().getContextClassLoader().getResourceAsStream();
//byte[] input = new byte[2048];
URL uri = Thread.currentThread().getContextClassLoader().getResource("");
File file = new File(uri.getPath()+File.separator+"WHATSNEW.zip");
FileInputStream fizip = new FileInputStream(file);
byte[] buffer2 = IOUtils.toByteArray(fizip);
bus.write(buffer2);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
}
}