HTTPBuilder and MultipartEntity / multipart form-data in Groovy

谁说胖子不能爱 提交于 2019-12-07 04:25:05

问题


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?


回答1:


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




回答2:


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)
        }
    }
}



回答3:


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.



来源:https://stackoverflow.com/questions/6452678/httpbuilder-and-multipartentity-multipart-form-data-in-groovy

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