Java:将多部分文件发送到 RESTWebservice

Ron*_*nie 5 java spring web-services httpclient apache-commons-httpclient

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

在此处输入图片说明

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

在第二个块中,有 RESTFul Webservice,它以 Multipart File 作为参数并对其进行处理。(到此为止已经完成了)。
现在我被困在这里。我想将此多部分文件发送到其他仅使用多部分文件的 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();
}

}
Run Code Online (Sandbox Code Playgroud)

问题:如何使用 HttpClient 将多部分文件发送到 RESTFul Web 服务?

Gar*_*rry 2

你能检查这个文件上传 apache http 客户端吗?

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);
Run Code Online (Sandbox Code Playgroud)

来源