martes, 14 de mayo de 2013

Multipart message with jersey

Hi there, so I'm really happy to see that there is people at least accessing this blog.
Honestly I was intented only for me but if it helps others BRILLIANT, one thing though: DO COMMENT.

Most useful data is usually find in the comments.

Now to today's topic: multi part messages.
In short multipart is a message that could be compose by more than one content type.
All this is part of the HTTP specification and in different RFC of it the guys creating the specification had defined different multiparts.

Today I'll show you how to handle two of them, which are more or less the same, with Jersey Client.



MULTIPART-MIXED
In this example I'll be sending a form with part of the message as XML and the other is the content of a file encoded in BASE64.

            // Asume that this method will just return you a builder 
        WebResource.Builder builder = getBuilder(user, password, url, null);

        // Add headers
        builder = builder.type(MultiPartMediaTypes.MULTIPART_MIXED);

        MultiPart multiPart = new MultiPart();

        // XML Document

         String xmlContent = getXMLContent();
         multiPart = multiPart.bodyPart(new BodyPart(xmlContent, MediaType.APPLICATION_XML_TYPE));

        // File content
        BodyPart bodyPart = new BodyPart();
        multiPart = multiPart.bodyPart(bodyPart);


        InputStream fileInputStream = getFileInputStream();
        bodyPart.setEntity(getFileContentInBase64(fileInputStream));

        ClientResponse clientResponse = builder.post(ClientResponse.class, multiPart);




MULTIPART-FORMDATA
For this example I'll be just sending some plaint text fields in the form and then the content of a file.

            // Asume that this method will just return you a builder 
        WebResource.Builder builder = getBuilder(user, password, url, null);

        // Add headers
        builder = builder.type(MediaType.MULTIPART_FORM_DATA);

        FormDataMultiPart form = new FormDataMultiPart();
        form.field("document[file_name]", fileName);
        form.field("document[description]", fileDescription);
        form.bodyPart(new StreamDataBodyPart("document[attached_file]", fileInputStream));

        ClientResponse clientResponse = builder.post(ClientResponse.class, form);




As you can see there is not much difference but the content-type header.
The other big difference is that the multipart-formdata does has the shape of a form.
This is you set a name of a property in the form and it's value.

But in multipart-mixed you just add body parts that can be what ever you want.
Of corse under the hod the serialized message looks quite different. In the mixed message you'll see some separators and the fact that the file is encoded, this is plain text but encoded.

Any ways this may save you some time.

Hope you like it.      

No hay comentarios:

Publicar un comentario