spring : get response as Multipart File from REST WebService
<p>I am creating POC for RESTFUL Web service using Spring 4.0. <strong>Requirement is to receive MultipartFile as Response from REST WEB-Service.</strong></p>

<p><strong>REST Service Controller</strong></p>

<pre><code>@RequestMapping(value="/getcontent/file", method=RequestMapping.post)
public MultipartFile getMultipartAsFileAsObject() {

    File file = new File("src/test/resources/input.docx");
    FileInputStream input = new FileInputStream(file);
    MultipartFile multipartFile = new MockMultipartFile("file",file.getName(),
                                 "application/docx", IOUtils.toByteArray(input));

    return multipartFile        
}
</code></pre>

<p>I call this service using third party Clients and Apache Http Client as well. kindly have a look on output.</p>

<p><strong>Using Third party REST client ie. Postman</strong></p>

<p>output looks like Json - </p>

<pre><code>{
    "name" : "file",
    "originalfilename" : "sample.docx",
    "contentType" : "application/docx",
    "content" : [
                82,
                101,
                97,
                100,
                101,    
                32,
                32,
                .
                .
                .
                .
                .
            ]  
}
</code></pre>

<p><strong>Apache HTTP Client Sample code</strong></p>

<pre><code>private static void executeClient() {
HttpClient client = new DefaultHttpClient();
HttpPost postReqeust = new HttpPost(SERVER_URI);

try{
    // Set Various Attributes

    HttpResponse response = client.execute(postReqeust) ;

    //Verify response if any
    if (response != null)
    {
        InputStream inputStream = response.getEntity().getContent();
        byte[] buffer = new byte[inputStream.available()];
        inputStream.read(buffer);

        OutputStream outputStream = new FileOutputStream
                                   (new File("src/main/resource/sample.docx"));
        outputStream.write(buffer);
        outputStream.flush();
        outputStream.close();
    }

}
catch(Exception ex){
    ex.printStackTrace();
}
</code></pre>

<p><strong>Output of Apache Http client</strong></p>

<p>file is getting Created but It is empty. (0 bytes).</p>