Groovy中的HTTPBuilder和MultipartEntity / multipart表单数据

|| 尝试模拟需要将一些INPUT / TEXT字段与文件中的数据结合在一起的HTTP POST。看起来我可以拥有一个,但不能同时拥有两个? 在下面的代码段中,paramsToPost = [名称:\'John \',年龄: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
}
有人有工作样品吗?     
已邀请:
        刚让我的代码可以使用较旧的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}\" )
}
希望这可以帮助     
        
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)
        }
    }
}
    
        对于寻找答案的任何其他人,请使用HTTPBuilder的此fork。 https://github.com/berngp/httpbuilder/tree/branch%2Fadd%2FMultiPart-Form 在某个时候,我希望它可以合并到主分支中。     

要回复问题请先登录注册