Groovy HTTP builder for sending multipart file.

31 / Aug / 2012 by Divya Setia 2 comments

I had two applications that communicate with each other through web-services. There I had a requirement to send multi-part file from one application to another. After searching I came out with the following solution and thought to share:

[java]
import org.apache.http.entity.mime.MultipartEntity
import org.apache.http.entity.mime.HttpMultipartMode
import org.apache.http.entity.mime.content.InputStreamBody
import org.apache.http.entity.mime.content.StringBody
import groovyx.net.http.*

void sendMultiPartFile(CommonsMultipartFile multipartImageFile, String cityName) {

def http = new HTTPBuilder("http://www.anotherapp.com/controller/action")

http.request(Method.POST) { req ->

requestContentType: "multipart/form-data"

MultipartEntity multiPartContent = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE)

// Adding Multi-part file parameter "imageFile"

multiPartContent.addPart("imageFile", new InputStreamBody(multipartImageFile.inputStream, multipartImageFile.contentType, multipartImageFile.originalFilename))

// Adding another string parameter "city"

multiPartContent.addPart("city", new StringBody(cityName))

req.setEntity(multiPartContent)

response.success = { resp ->

if (resp.statusLine.statusCode == 200) {

// response handling

}
}
}
}

[/java]

Hope it would help!!!
~~
Regards
Divya Setia
divya@intelligrape.com

FOUND THIS USEFUL? SHARE IT

comments (2)

Leave a Reply

Your email address will not be published. Required fields are marked *