我正在尝试通过从 gradle 构建的独立 groovy 测试脚本创建和发送多部分请求来测试我的 Grails Web 应用程序。但我在挣扎。
编辑(感谢至强):
这是我的代码:
独立测试脚本代码:
void sendMultipartRequest(String url) {
HTTPBuilder httpBuilder = new HTTPBuilder(url)
httpBuilder.request(Method.POST){ req ->
MultipartEntityBuilder entityBuilder = new MultipartEntityBuilder()
entityBuilder.setBoundary("----boundary")
entityBuilder.setMode(HttpMultipartMode.RFC6532)
String randomString = myGenerateRandomStringMethod()
FormBodyPart formBodyPart = new FormBodyPart(
"SOME_NAME",
new InputStreamBody(new ByteArrayInputStream(randomString.bytes), "attachment", "SOME_NAME")
)
formBodyPart.addField("Content-ID", "abc123")
entityBuilder.addPart(formBodyPart)
response.success = { resp ->
println("Success with response ${resp.toString()}")
}
response.failure = { resp ->
println("Failure with response ${resp.toString()}")
}
delegate.setHeaders(["Content-Type":"multipart/related; boundary=----boundary"])
req.setEntity(entityBuilder.build())
}
}
Controller 中用于处理帖子的 Grails web-app 端:
def submitFiles() {
if(request instanceof MultipartHttpServletRequest){
HashMap<String, Byte[]> fileMap = extractMultipartFiles(request)
someService.doStuffWith(fileMap)
}
}
private HashMap<String, Byte[]> extractMultipartFiles(MultipartHttpServletRequest multipartRequest) {
HashMap<String, Byte[]> files = new HashMap<>()
for(element in mulipartRequest.multiFileMap){
MultipartFile file = element.value.first()
String contentId = multipartRequest.getMultipartHeaders(element.key).get("Content-ID")?.first()
if(contentId) files.put(contentId, file.getBytes())
}
return files
}
我正在使用的库:
ext {
groovyVersion = "2.3.4"
commonsLangVersion = "2.6"
httpBuilderVersion = "0.7.1"
httpmimeVersion = "4.3.4"
junitVersion = "4.11"
}
dependencies {
compile "org.codehaus.groovy:groovy-all:${groovyVersion}"
compile "commons-lang:commons-lang:${commonsLangVersion}"
compile "org.codehaus.groovy.modules.http-builder:http-builder:${httpBuilderVersion}"
compile "org.apache.httpcomponents:httpmime:${httpmimeVersion}"
testCompile group: 'junit', name: 'junit', version: "${junitVersion}"
}
最佳答案
你总是可以使用 ContentBody
的一些子类。界面:
FormBodyPart(String name, ContentBody body)
例如使用:
InputStreamBody
:new FormBodyPart("name", new InputStreamBody(new RandomInputStream(...)), ContentType.MULTIPART_FORM_DATA);
您可以使用:RandomInputStream类(class)。
对于标题,您可能会使用:
HTTPBuilder$RequestConfigDelegate.setHeaders(Map headers)
因为它被设置为内部闭包的委托(delegate)。
关于grails - Groovy 脚本向 Grails Web App 发送多部分请求以进行测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25430966/