gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 09:25:34 24 4
gpt4 key购买 nike

好像有几个帖子,例如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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com