HTTPBuilder and MultipartEntity / multipart form-data in Groovy

Sunny picture Sunny · Jun 23, 2011 · Viewed 7.6k times · Source

Trying to simulate a HTTP POST that needs to combine some INPUT/TEXT fields along with data from a file. It looks like I can have one or the other, but not both?

In the snippet below, paramsToPost = [name: 'John', age:22]

@Grab(group='org.codehaus.groovy.modules.http-builder', module='http-builder', version='0.5.0')
Boolean doHttpPost(String url, Map paramsToPost, String fileContent) {
    HTTPBuilder http = new HTTPBuilder(url)
    def resp = http.request(Method.POST ) { req ->
        MultipartEntity mpe = new MultipartEntity()
        mpe.addPart "foo", new StringBody(fileContent)
        req.entity = mpe

        // body = paramsToPost // no such property
    }

    println "response: ${resp}"

    return true
}

Anybody have a working sample please?

Answer

Irina A picture Irina A · Aug 11, 2011

just got my code to work with the older commons-httpclient-3.1.jar

 (new HTTPBuilder(url)).request(Method.POST) { request ->
MultipartEntity mpe = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
mpe.addPart('fileInput', new StringBody(params.fileInput))
if (params.fileInput=='file')
    mpe.addPart('file1', new InputStreamBody(uploadedFile.inputStream, uploadedFile.contentType, uploadedFile.originalFilename))
else if (params.fileInput=='text')
    mpe.addPart('fileText', new StringBody(params.fileText))
mpe.addPart('tags1', new StringBody(params.tags1)) 
request.entity = mpe
request.getParams().setParameter("http.connection.timeout", HTTP_TIMEOUT)
request.getParams().setParameter("http.socket.timeout", HTTP_TIMEOUT)
response.success = { resp, reader ->
    render(text : "Successfully uploaded file\n\n${reader.text}")
}
response.failure = { resp ->
  render (status: 500, text: "HTTP Failure Accessing Upload Service ${resp.statusLine}" )
}

hope this helps