HTTPBuilder和MultipartEntity / multipart form-data在Groovy中的应用

5

我想模拟一个需要将一些输入/文本字段与文件数据组合的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
}

有没有现成的样例可以提供?
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}" )
}

希望这可以帮助到您


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

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接