4

I have a Jersey service that output binary data as StreamingOutput, MediaType.APPLICATION_OCTET_STREAM.

How to implement a client using Jersey 2 for handling the response from such service?

Vikas Sachdeva
  • 5,633
  • 2
  • 17
  • 26
sunish
  • 61
  • 3
  • There is a Client API section in Jersey Docs, look at this example: https://jersey.java.net/documentation/latest/client.html#d0e4349 – vadchen Mar 06 '14 at 07:26

1 Answers1

1

Below is one way of implementing Jersey 2 client for downloading a file from a REST service which is returning binary data as StreamingOutput with MediaType.APPLICATION_OCTET_STREAM -

    Client client = ClientBuilder.newClient();
    // change SERVER_URL, API_PATH and PATH as per REST API details
    WebTarget webTarget = client.target(SERVER_URL).path(API_PATH).path(PATH);

    Invocation.Builder invocationBuilder = webTarget.request();
    Response response = invocationBuilder.get();

    String contentDispositionHeader = response.getHeaderString("Content-Disposition");
    String fileName = contentDispositionHeader
            .substring(contentDispositionHeader.indexOf("filename=") + "filename=".length()).replace("\"", "");

    InputStream responseStream = response.readEntity(InputStream.class);

    // Set location here where you want to store downloaded file. 
    // It will replace the file if already exist in that location with same name.
    Files.copy(responseStream, Paths.get("H:/"+ fileName), StandardCopyOption.REPLACE_EXISTING);

    System.out.println("File is downloaded");
Vikas Sachdeva
  • 5,633
  • 2
  • 17
  • 26