6

I have a java controller which have to send me some text data and different byte arrays. So I am building n multipart request and writing it to stream from HttpServletResponse.

Now my problem is how to parse the response at client side and extract the multiple parts.

SERVER CODE SNIPPET:-

        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        // Prepare payload
        builder.addBinaryBody("document1", file);
        builder.addBinaryBody("document2", file2);
        builder.addPart("stringData", new StringBody(jsonData, ContentType.TEXT_PLAIN));

        // Set to request body

        HttpEntity entity = builder.build();
        postRequest.setEntity(entity);

CLIENT CODE SNIPPET:-

        HttpPost httpPost = new HttpPost(finalUrl);

        StringEntity entity = new StringEntity(json);
        httpPost.setEntity(entity);
        httpPost.setHeader("Content-type", APPLICATION_JSON_TYPE);

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        CloseableHttpResponse response = httpClient.execute(httpPost);
        InputStream in = new BufferedInputStream(response.getEntity().getContent());

I checked CloseableHttpResponse and HttpEntity but none of them is providing method to parse multipart request.

EDIT 1: This is my sample response I am receiving at client side stream:-

--bvRi5oZum37DUldtLgQGSbc5RRVZxKpjZMO4SYDe
Content-Disposition: form-data; name="numeric"
Content-Type: text/plain; charset=ISO-8859-1
Content-Transfer-Encoding: 8bit
01010110
--bvRi5oZum37DUldtLgQGSbc5RRVZxKpjZMO4SYDe
Content-Disposition: form-data; name="stringmessage"
Content-Type: text/plain; charset=ISO-8859-1
Content-Transfer-Encoding:8bit
testmessage
--bvRi5oZum37DUldtLgQGSbc5RRVZxKpjZMO4SYDe
Content-Disposition: form-data; name="binarydata"; filename="file1"
Content-Type: application/octet-stream
Content-Transfer-Encoding: binary
HI, THIS IS MY BINARY DATA
--bvRi5oZum37DUldtLgQGSbc5RRVZxKpjZMO4SYDe
Content-Disposition: form-data; name="ending"
Content-Type: text/plain; charset=ISO-8859-1
Content-Transfer-Encoding: 8bit
ending
--bvRi5oZum37DUldtLgQGSbc5RRVZxKpjZMO4SYDe--
kleash
  • 1,061
  • 1
  • 9
  • 28
  • I believe this can help you: http://stackoverflow.com/questions/3337056/convenient-way-to-parse-incoming-multipart-form-data-parameters-in-a-servlet – Boschi Mar 01 '17 at 14:18
  • @Boschi Fileupload API methods accept HTTPServletRequest which is not possible in my case as it's a response from the servlet. Please let me know if I am missing some point here. – kleash Mar 02 '17 at 05:27
  • I have added a sample message response received at client.. – kleash Mar 02 '17 at 05:42

2 Answers2

19

I have finally got a workaround for it.

I will be using javax mail MimeMultipart.

Below is a code snipped for the solution:-

    ByteArrayDataSource datasource = new ByteArrayDataSource(in, "multipart/form-data");
    MimeMultipart multipart = new MimeMultipart(datasource);

    int count = multipart.getCount();
    log.debug("count " + count);
    for (int i = 0; i < count; i++) {
        BodyPart bodyPart = multipart.getBodyPart(i);
        if (bodyPart.isMimeType("text/plain")) {
            log.info("text/plain " + bodyPart.getContentType());
            processTextData(bodyPart.getContent());
        } else if (bodyPart.isMimeType("application/octet-stream")) {
            log.info("application/octet-stream " + bodyPart.getContentType());
            processBinaryData(bodyPart.getInputStream()));
        } else {
            log.warn("default " + bodyPart.getContentType());
        }
    }

Please let me know if anybody else have any standard solution.

kleash
  • 1,061
  • 1
  • 9
  • 28
  • 1
    You are a genius man. I was looking for this for 3 days. Its sad to see java has no standard in their Apache libraries for reading multi-part data or that jaxrs has no standard either. this was simple to use and only took three jars. – yfdgvf asdasdas Oct 10 '18 at 15:15
  • @yfdgvfasdasdas Thanks for your kind words :) – kleash Oct 10 '18 at 15:40
  • it is not working when i try to parse the lambda response of multipart/form-data.. :(Is there anyother alternative to it – Ak S Nov 23 '18 at 12:17
  • @AkS I tried it with sending a JSON as string and 2 pdf and it worked fine here.. – kleash Nov 24 '18 at 03:50
  • @LeiYang, Which classes are you talking about. I was not using com.sun.xml package anywhere... – kleash May 07 '19 at 07:04
0

Mime4j from Apache is one way to parse the responses from client-side. Its a common practice to use a tool like this.

You can refer this link - http://www.programcreek.com/java-api-examples/index.php?api=org.apache.james.mime4j.MimeException

You can download the jar from this link - http://james.apache.org/download.cgi#Apache_Mime4J

Hope this helps. Cheers

Vijayan Kani
  • 348
  • 2
  • 8
  • I tried with it but it's not able to parse the stream. Most probably because it's expecting in different way. I have added a sample message response received at client – kleash Mar 02 '17 at 05:42