Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTTPBuilder and MultipartEntity / multipart form-data in Groovy

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?

like image 778
Sunny Avatar asked Oct 10 '22 16:10

Sunny


1 Answers

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

like image 175
Irina A Avatar answered Oct 13 '22 22:10

Irina A