spring - Apache HttpClient 向 Spring @Controller 类进行多部分 POST

标签 spring file-upload httpclient multipart multipartform-data

好像有几个帖子,例如here询问如何在 Java 中使用 Apache Commons HTTPClient 库对 Servlet 执行 POST。然而,我似乎在使用带注释的 Spring Controller 方法做同样的事情时遇到了一些问题。我尝试了一些方法,但从服务器收到了 HTTP 401 错误请求响应。任何这样做的例子将不胜感激。

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

//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。

最佳答案

当它表现出无能时,我讨厌回答我自己的问题,但事实证明代码很好,这个特定的 Controller 没有在其 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>

关于spring - Apache HttpClient 向 Spring @Controller 类进行多部分 POST,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4894508/

相关文章:

java - Spring映射问题

java - Spring @RequestBody 不使用 pojo?

java - Jersey 客户端读取超时,但 Apache HTTP 客户端连接正常

spring - 分布式 spring 应用程序中的身份验证和 session 管理

database - 手动为 hibernate UUID 赋值

php - 通过 PHP 上传 ZIP 文件和 UNZIP ftp 文件夹

angular - 与以前的 Http 相比,Angular 5 HttpClient 有哪些优势?

oauth - 获取 Zoho API 的授权

java - 如何实现递归的拖放文件/文件夹上传?

python - 如何使用 Flask-RESTPlus 发布多个文件?