5

试图模拟需要将一些 INPUT/TEXT 字段与文件中的数据结合起来的 HTTP POST。看起来我可以拥有一个或另一个,但不能同时拥有?

在下面的代码段中,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
}

请问有人有工作样品吗?

4

3 回答 3

3

刚刚让我的代码与旧的 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}" )
}

希望这可以帮助

于 2011-08-10T23:18:10.240 回答
1
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)
        }
    }
}
于 2018-05-24T08:31:13.200 回答
0

对于其他正在寻找答案的人,请使用 HTTPBuilder 的这个分支。

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

在某些时候,我希望这会合并到主分支中。

于 2011-06-26T23:18:32.760 回答