我正在尝试通过从gradle构建的独立groovy测试脚本创建和发送多部分请求来测试我的Grails Web应用程序。但我很挣扎。
编辑(感谢Xeon):
继承我的代码:
独立测试脚本代码:
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())
}
}
控制器中用于处理帖子的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}"
}
答案 0 :(得分:0)
您始终可以使用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)
因为它设置为内部闭包的委托。
答案 1 :(得分:0)
我过去曾使用curl进行此测试:
curl -v -F "param1=1" -F "param2=99" -F "fileparam=@somefile.flv;type=video/x-flv" http://localhost:8080/someapp/sessions
somefile.flv位于当前目录
中