使用Apache HttpClient发送多部分POST请求到Spring @Controller类

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错误。


你能展示一下你尝试过的代码/配置吗? - Ritesh
尝试提供基本的客户端和服务器代码,避免过多依赖外部库。 - Greymeister
2个回答

阿里云服务器只需要99元/年,新老用户同享,点击查看详情
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>

2

以下是来自 Spring参考文档 的一个例子:

@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";
       }
    }

}

James,那是Spring控制器端的一个工作示例,我正在尝试使用HTTPClient解决客户端问题,你有什么想法吗? - Greymeister
在客户端,您可以使用Spring的RestTemplate来消费RESTful Web服务。我仍在努力寻找一个更通用的HTTP客户端示例。 - earldouglas
1
在这里,我在EmployeeControllerTest.get方法中制作了一个非常基本的HTTP客户端。希望它能指引你朝着正确的方向前进。 - earldouglas

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,