Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jersey client to download and save file

I Am new to jersey/JAX-RS implementation. Please find below my jersey client code to download file:

 Client client = Client.create();
 WebResource wr = client.resource("http://localhost:7070/upload-0.0.1-SNAPSHOT/rest/files/download");
 Builder wb=wr.accept("application/json,application/pdf,text/plain,image/jpeg,application/xml,application/vnd.ms-excel");
 ClientResponse clientResponse= wr.get(ClientResponse.class);
 System.out.println(clientResponse.getStatus());
 File res= clientResponse.getEntity(File.class);
 File downloadfile = new File("C://Data/test/downloaded/testnew.pdf");  
 res.renameTo(downloadfile);
 FileWriter fr = new FileWriter(res);
 fr.flush();

My Server side code is :

@Path("/download")
    @GET
    @Produces({"application/pdf","text/plain","image/jpeg","application/xml","application/vnd.ms-excel"})
    public Response getFile()
    {

        File download = new File("C://Data/Test/downloaded/empty.pdf");
        ResponseBuilder response = Response.ok((Object)download);
        response.header("Content-Disposition", "attachment; filename=empty.pdf");
        return response.build();
    }

In my client code i am getting response as 200 OK,but i am unable to save my file on hard disk In the below line i am mentioning the path and location where the files need to be saved. Not sure whats going wrong here,any help would be appreciated.Thanks in advance!!

File downloadfile = new File("C://Data/test/downloaded/testnew.pdf");
like image 286
cxyz Avatar asked Jul 12 '14 19:07

cxyz


People also ask

Is Jersey client thread safe?

Yes, the Jersey 2.1 client is thread safe and it should be thread safe even in the future Jersey version. You can create many WebTarget from one Client instance and invoke many requests on these WebTargets and even more requests on one WebTarget instance in the same time.

What is Jersey Apache client?

Jersey is a REST-client, featuring full JAX-RS implementation, neat fluent API and a powerfull filter stack. Apache Http Client is a HTTP-client, perfect in managing low-level details like timeouts, complex proxy routes and connection polling. They act on a different levels of your protocol stack.

What is Jersey client API?

Jersey ClientBuilder. JAX-RS Client API is a designed to allow fluent programming model. To create jersey client follow these steps – Use ClientBuilder. newClient() static method.


2 Answers

For folks still looking for a solution, here is the complete code on how to save jaxrs response to a File.

public void downloadClient(){
    Client client = ClientBuilder.newClient();
    WebTarget target = client.target("http://localhost:7070/upload-0.0.1-SNAPSHOT/rest/files/download");

    Response resp = target
      .request("application/pdf,image/jpeg,application/xml,application/vnd.ms-excel")
      .get();

    if(resp.getStatus() == Response.Status.OK.getStatusCode())
    {
        InputStream is = resp.readEntity(InputStream.class);
        fetchFeed(is); 
        //fetchFeedAnotherWay(is) //use for Java 7
        IOUtils.closeQuietly(is);
        System.out.println("the file details after call:"+downloadfile.getAbsolutePath()+", size is "+downloadfile.length());
    } 
    else{
        throw new WebApplicationException("Http Call failed. response code is"+resp.getStatus()+". Error reported is"+resp.getStatusInfo());
    }
}
/**
* Store contents of file from response to local disk using java 7 
* java.nio.file.Files
*/
private void fetchFeed(InputStream is){
    File downloadfile = new File("C://Data/test/downloaded/testnew.pdf");  
    byte[] byteArray = IOUtils.toByteArray(is);
    FileOutputStream fos = new FileOutputStream(downloadfile);
    fos.write(byteArray);
    fos.flush();
    fos.close();
}

/**
* Alternate way to Store contents of file from response to local disk using
* java 7, java.nio.file.Files
*/
private void fetchFeedAnotherWay(InputStream is){
    File downloadfile = new File("C://Data/test/downloaded/testnew.pdf");  
    Files.copy(is, downloadfile.toPath(), StandardCopyOption.REPLACE_EXISTING);
}
like image 182
pNut Avatar answered Oct 23 '22 23:10

pNut


I don't know if Jersey let's you simply respond with a file like you have here:

File download = new File("C://Data/Test/downloaded/empty.pdf");
ResponseBuilder response = Response.ok((Object)download);

You can certainly use a StreamingOutput response to send the file from the server, like this:

StreamingOutput stream = new StreamingOutput() {
    @Override
    public void write(OutputStream os) throws IOException,
    WebApplicationException {
        Writer writer = new BufferedWriter(new OutputStreamWriter(os));

        //@TODO read the file here and write to the writer

        writer.flush();
    }
};

return Response.ok(stream).build();

and your client would expect to read a stream and put it in a file:

InputStream in = response.getEntityInputStream();
if (in != null) {
    File f = new File("C://Data/test/downloaded/testnew.pdf");

    //@TODO copy the in stream to the file f

    System.out.println("Result size:" + f.length() + " written to " + f.getPath());
}
like image 4
Paul Jowett Avatar answered Oct 23 '22 22:10

Paul Jowett