gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 15:21:50 27 4
gpt4 key购买 nike

尝试模拟需要将一些 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
}

有人有工作样本吗?

最佳答案

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

希望对你有帮助

关于Groovy 中的 HTTPBuilder 和 MultipartEntity/multipart 表单数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6452678/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com