Spring WebClient: How to stream large byte[] to file?

后端 未结 4 934
天命终不由人
天命终不由人 2021-02-02 17:11

It seems like it the Spring RestTemplate isn\'t able to stream a response directly to file without buffering it all in memory. What is the proper to achieve this us

4条回答
  •  心在旅途
    2021-02-02 17:22

    I'm not sure if you have access to RestTemplate in your current usage of spring, but this one have worked for me.

    
    RestTemplate restTemplate // = ...;
    
    RequestCallback requestCallback = request -> request.getHeaders()
            .setAccept(Arrays.asList(MediaType.APPLICATION_OCTET_STREAM, MediaType.ALL));
    
    // Streams the response
    ResponseExtractor responseExtractor = response -> {
        // Here I write the response to a file but do what you like
        Path path = Paths.get("http://some/path");
        Files.copy(response.getBody(), path);
        return null;
    };
    restTemplate.execute(URI.create("www.something.com"), HttpMethod.GET, requestCallback, responseExtractor);
    
    

提交回复
热议问题