HTTPBuilder and MultipartEntity / multipart form-data in Groovy

我只是一个虾纸丫 提交于 2019-12-05 11:04:20

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

def postMultipartForm(String uri,
                      File file,
                      String filePartName,
                      Map<String, String> textFields = [:],
                      Map<String, String> httpHeaders = [:]) {
    MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create()
            .addPart(filePartName, new FileBody(file, ContentType.APPLICATION_XML.withCharset(StandardCharsets.UTF_8)))
    textFields.each { n, v -> entityBuilder.addTextBody(n, v) }

    final expectedResponseContentType = ContentType.ANY
    return new HTTPBuilder().request(uri, Method.POST, expectedResponseContentType) { HttpEntityEnclosingRequest req ->
        req.entity = entityBuilder.build()
        httpHeaders.each { h, v ->
            req.addHeader(h, v)
        }
    }
}

For anybody else looking for an answer, use this fork of the HTTPBuilder.

https://github.com/berngp/httpbuilder/tree/branch%2Fadd%2FMultiPart-Form

At some point, I'd expect this to be merged into the main branch.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!