Java:将Multipart文件发送到RESTWebservice

时间:2015-06-24 05:30:29

标签: java spring web-services httpclient apache-commons-httpclient

我使用 Spring 作为技术。用于调用Webservice的 Apache HttpClient 。基本目的是上传多部分文件(文件不是任何图像文件或视频文件)。但这里我的要求略有不同。请查看下图。

enter image description here

这里你可以看到第一块。它是一个简单的GUI,只有2个输入标签和正确的表格标签。

在第二个块中,有RESTFul Webservice,它将Multipart File作为参数并进行处理。 (到此为止)。
现在我被困在这里。我想将此Multipart文件发送到仅使用Multipart文件的其他RESTFul Web服务。

RESTFUL Webservice的代码片段:(评论了一些问题,需要你的建议)

@RequestMapping(value="/project/add")
public @ResponseBody String addURLListToQueue(
        @RequestParam(value = "file") MultipartFile file,
        @RequestParam(value = "id1", defaultValue = "notoken") String projectName,
        @RequestParam(value = "id2", defaultValue = "notoken") String id2,
        @RequestParam(value = "id3", defaultValue = "notoken") String id3){

HttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);

HttpPost httppost = new HttpPost("http://localhost:8080/fs/project/add");

// 1) Do I need to convert it into File object? (tried but faced 400 Error)
// 2) Is there any provision to send Multipart File as it is?

MultipartEntity mpEntity = new MultipartEntity();
ContentBody cbFile = new FileBody(file, "multipart/form-data");
mpEntity.addPart("file", cbFile);


httppost.setEntity(mpEntity);
System.out.println("executing request " + httppost.getRequestLine());
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();

System.out.println(response.getStatusLine());
if (resEntity != null) {
  System.out.println(EntityUtils.toString(resEntity));
}
if (resEntity != null) {
  resEntity.consumeContent();
}

httpclient.getConnectionManager().shutdown();
}

}

问题:如何使用HttpClient将Multipart文件发送到RESTFul Webservice?

1 个答案:

答案 0 :(得分:1)

您可以查看file upload apache http client吗?

另外

HttpPost post = new HttpPost("http://echo.200please.com");
InputStream inputStream = new FileInputStream(zipFileName);
File file = new File(imageFileName);
String message = "This is a multipart post";
MultipartEntityBuilder builder = MultipartEntityBuilder.create();         
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
builder.addBinaryBody
  ("upfile", file, ContentType.DEFAULT_BINARY, imageFileName);
builder.addBinaryBody
  ("upstream", inputStream, ContentType.create("application/zip"), zipFileName);
builder.addTextBody("text", message, ContentType.TEXT_PLAIN);
// 
HttpEntity entity = builder.build();
post.setEntity(entity);
HttpResponse response = client.execute(post);

Source