3

似乎有几个帖子,例如这里询问如何在 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。

4

2 回答 2

4

当它显示无能时,我讨厌回答我自己的问题,但事实证明代码很好,这个特定的控制器没有在其 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>
于 2011-02-04T17:15:02.147 回答
2

这是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";
       }
    }

}
于 2011-02-04T04:38:16.897 回答