Thursday, June 20, 2013

Multipart file upload in Groovy HTTPBuilder

HttpClient from HttpComponents is very powerful, but super ugly library. Groovy has nice wrapper around it, called HTTPBuilder, which looks better and has DSLish API. It is just as powerful as HttpClient, as it is using it underneath. Unfortunately, it has far less documentation and bad googleability.
For example I tried to use it for file upload, and it is not in original documentation, and nothing sane on StackOverflow or likes. Fortunately, it is still possible and easy (despite HttpClient ugliness creeping in).

    def http = new HTTPBuilder( 'http://localhost:8080/' )
    http.auth.basic 'test', '123456'
    http.request( POST, JSON ) { req ->
      uri.path = '/project/addFile'
      uri.query = [ id:projectId ]
      requestContentType = 'multipart/form-data'
      MultipartEntity entity = new MultipartEntity()
      entity.addPart("file", new ByteArrayBody("123456".getBytes("UTF-8"), 'filename.jpg'))
      req.entity = entity
    }