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