尝试模拟需要将一些INPUT / TEXT字段与文件中的数据组合在一起的HTTP POST。看起来我可以有一个或另一个,但不是两个?
在下面的代码段中,paramsToPost = [name:'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
}
有人有工作样品吗?
答案 0 :(得分: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 :(得分:1)
Function::identity
答案 2 :(得分:0)
对于寻找答案的其他人,请使用HTTPBuilder的这个分支。
https://github.com/berngp/httpbuilder/tree/branch%2Fadd%2FMultiPart-Form
在某些时候,我希望将它合并到主分支中。