Monday, January 16, 2017

RestBuilder client large file downloads

I have a Grails 2.x project using the RestBuilder plugin, and I had a use case which required downloading of large data files as client of a remote RESTful webservice. However the documentation for supporting binary downloads was scarce and painstakingly took long hours of trolling through API code of both Spring and RestBuilder. So I'd like to share with others what I did to get this working:

      def void download(String url, OutputStream outputStream) {            
           logger.info("url="+url)  
           RequestCallback requestCallback = new RequestCallback() {  
                void doWithRequest(ClientHttpRequest clientRequest) throws IOException {  
                     clientRequest.headers.add('accept', 'application/octet-stream')             
                }  
           }  
           ResponseExtractor responseExtractor = new ResponseExtractor() {  
                Object extractData(ClientHttpResponse clientResponse) throws IOException {  
                     System.out.println('Headers: '+clientResponse.headers)  
                     outputStream << clientResponse.body  
                }  
           }  
           RestBuilder rest = new RestBuilder()  
           RestTemplate restTemplate = rest.getRestTemplate()  
           restTemplate.execute(url, HttpMethod.GET, requestCallback, responseExtractor)                                
      }  


I had to fallback to using Spring's RestTemplate class and barely used any of the RestBuilder plugin to implement the solution.

It's the ResponseExtractor anonymous class that does the most important job of routing the InputStream from the response to an OutputStream.


Reference: https://stackoverflow.com/questions/32988370/download-large-file-from-server-using-rest-template-java-spring-mvc/38664475#38664475

No comments:

Post a Comment