Search code examples
javarestmultipartjersey-client

Jersey Client for Mulipart call


I am using jersey client to make a REST call to an API which returns a Json and a PDF file in mulipart as the first and the second parts of the response.

final Client client = ClientBuilder.newClient();
final WebTarget target = client.target(endPoint);
final Builder request = target.request().header("Authorization", authKey);
final Response response = request.get();
final String readEntity = response.readEntity(String.class);

This returns a string response with the PDF file in byte code format. I tried to read the entity as MultiPart class and then I get an exception :

Message Body Reader Not found for media type=multipart/form-data;boundary=------#### and the getMediaType() call on client returns multipart/form-data;boundary=------####.

What is the right way to parse this multipart response using the above client?


Solution

  • A quick Google search gives you the result. You have to enable MultiPartFeature and you do response.readEntity(InputStream.class)

    Got the below code from http://www.benchresources.net/jersey-2-x-web-service-for-uploadingdownloading-zip-file-java-client/

     // invoke service after setting necessary parameters
            clientConfig = new ClientConfig();
            clientConfig.register(MultiPartFeature.class);
            client =  ClientBuilder.newClient(clientConfig);
            client.property("accept", "application/zip");
            webTarget = client.target(httpURL);
    
            // invoke service
            invocationBuilder = webTarget.request();
            //          invocationBuilder.header("Authorization", "Basic " + authorization);
            response = invocationBuilder.get();
    
            // get response code
            responseCode = response.getStatus();
            System.out.println("Response code: " + responseCode);
    
            if (response.getStatus() != 200) {
                throw new RuntimeException("Failed with HTTP error code : " + responseCode);
            }
    
            // get response message
            responseMessageFromServer = response.getStatusInfo().getReasonPhrase();
            System.out.println("ResponseMessageFromServer: " + responseMessageFromServer);
    
            // read response string
            inputStream = response.readEntity(InputStream.class);
            qualifiedDownloadFilePath = DOWNLOAD_FILE_LOCATION + "MyJerseyZippedFile.zip";
            outputStream = new FileOutputStream(qualifiedDownloadFilePath);
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }