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?
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?
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");