encodinggroovymultipartform-datarest-clienthttpbuilder

encoder function for multipart/form-data in groovy


I need to form a 'multipart/form-data' REST request with jpeg image and JSON file as the content.I am stuck with encoding the 'multipart/form-data' as a zip file.

Can someone tell me, how I can achieve this with groovy RESTClient? I could not find any documentation regarding this.


Solution

  • As it can be seen in the docs RESTClient extends HTTPBuilder. HTTPBuilder has a getEncoder method that can be used to add dedicated encoder (with type and method). See the following piece of code:

    import org.codehaus.groovy.runtime.MethodClosure
    import javax.ws.rs.core.MediaType
    
    //this part adds a special encoder    
    def client = new RESTClient('some host')
    client.encoder.putAt(MediaType.MULTIPART_FORM_DATA, new MethodClosure(this, 'encodeMultiPart'))
    
    //here is the method for the encoder added above
    HttpEntity encodeMultiPart(MultipartBody body) {
        MultipartEntityBuilder.create()
        .addBinaryBody(
            'file', 
            body.file, 
            ContentType.MULTIPART_FORM_DATA, 
            body.filename
        ).build()
    }
    
    //here's how MultipartBody class looks:
    class MultipartBody {
       InputStream file
       String filename
    }
    

    Now to create a multipart request You need to pass an instance of MultipartBody as a body argument to the request.