Apache HttpClient对Spring @Controller类进行多部分POST

时间:2011-02-04 04:16:12

标签: spring file-upload httpclient multipart multipartform-data

似乎有几个帖子如here询问如何在Java中使用Apache Commons HTTPClient库来对Servlet进行POST。但是,看起来我在使用带注释的Spring控制器方法做同样的事情时遇到了一些问题。我尝试了一些东西,但从服务器获得了HTTP 401 Bad Request响应。任何这样做的例子都将非常感激。

编辑:我正在尝试使用的代码:

//Server Side (Java)
@RequestMapping(value = "/create", method = RequestMethod.POST)
public void createDocument(@RequestParam("userId") String userId,
                           @RequestParam("file") MultipartFile file, HttpServletResponse response) {
    // Do some stuff                            
}

//Client Side (Groovy)
    void processJob(InputStream stream, String remoteAddress) {
    HttpClient httpclient = new DefaultHttpClient()
    httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1)
    HttpPost httppost = new HttpPost("http://someurl/rest/create")

    MultipartEntity mpEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE)
    InputStreamBody uploadFilePart = new InputStreamBody(stream, 'application/octet-stream', 'test.file')
    mpEntity.addPart('file', uploadFilePart)
    mpEntity.addPart('userId', new StringBody('testUser'))
    httppost.setEntity(mpEntity)

    HttpResponse response = httpclient.execute(httppost);
    println(response.statusLine)
}

来自服务器的响应中仍然收到400 Bad Request。

2 个答案:

答案 0 :(得分:3)

当它显示无能时,我讨厌回答我自己的问题,但事实证明代码很好,这个特定的控制器没有在其servlet-context.xml文件中定义的CommonsMultipartResolver(多个DispatcherServlets ......长篇故事: ()

这是我为了让它发挥作用而添加的内容:

<!-- ========================= Resolver DEFINITIONS ========================= -->
<bean id="multipartResolver"
        class="org.springframework.web.multipart.commons.CommonsMultipartResolver">

    <!-- one of the properties available; the maximum file size in bytes -->
    <property name="maxUploadSize" value="50000000"/>
</bean>

答案 1 :(得分:2)

以下是the Spring Reference的示例:

@Controller
public class FileUpoadController {

    @RequestMapping(value = "/form", method = RequestMethod.POST)
    public String handleFormUpload(@RequestParam("name") String name,
        @RequestParam("file") MultipartFile file) {

        if (!file.isEmpty()) {
            byte[] bytes = file.getBytes();
            // store the bytes somewhere
           return "redirect:uploadSuccess";
       } else {
           return "redirect:uploadFailure";
       }
    }

}