Java : Send Multipart File to RESTWebservice

9.2k views Asked by At

I am using Spring as Technology. Apache HttpClient for calling Webservice. Basic purpose is to upload Multipart File(File is not any image file or video file). but Here My requirement is slightly different. Kindly check below image.

enter image description here

Here You can see first block. It is a simple GUI, having only 2 input tags along with proper form tag.

In second block, There is RESTFul Webservice, which takes Multipart File as parameter and process it. (Upto this it is done).
Now I am stuck here. I want to send this Multipart File to other RESTFul Webservice which consumes Multipart File only.

code Snippet of RESTFUL Webservice : (Commented some questions, need your suggestion)

@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();
}

}

Questions : How to send Multipart File to RESTFul Webservice using HttpClient?

1

There are 1 answers

0
Garry On

Can you check this file upload apache http client?

Also

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