我需要使用httpclient 4.5测试文件上传
以下方法用于上传文件:
public Response postwithFile(String url, File file) {
HttpPost postMethod = new HttpPost(PropertyUtil.loadEnvironment().getBaseUrl() + url);
postMethod.setHeader("Content-Type","multipart/form-data");
FileBody fileBody = new FileBody(file, ContentType.MULTIPART_FORM_DATA);
//_addAuthHeader(postMethod);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
// fileParamName should be replaced with parameter name your REST API expect.
builder.addPart("upfile", fileBody);
HttpEntity entity = builder.build();
postMethod.setEntity(entity) ;
return execute(postMethod);
}
文件没有任何扩展名,但文件的内容为JSON。
在调用上述方法时,我在服务器日志中收到500错误和以下异常:
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.springframework.web.multipart.MultipartException: Curren
t request is not a multipart request
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:982)
有人可以帮我做错什么吗?
答案 0 :(得分:1)
使用以下内容
builder.addBinaryBody(
"upfile",
new FileInputStream(file),
ContentType.APPLICATION_OCTET_STREAM,
file.getName()
);
代替
builder.addPart("upfile", fileBody);
由于已弃用以下内容,因此不再需要以下内容:-
FileBody fileBody = new FileBody(file, ContentType.MULTIPART_FORM_DATA);