Jersey 2 Client for StreamingOutput

I have a service Jerseythat displays the data as binary StreamingOutput, MediaType.APPLICATION_OCTET_STREAM.

How to implement a client using Jersey2 for processing responsefrom such a service?

+4
source share
1 answer

Below is one way to implement the Jersey 2 client to download a file from a REST service that returns binary data as StreamingOutputwith 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");
0
source

Source: https://habr.com/ru/post/1530374/


All Articles