如何在restTemplate-execute中设置HttpEntity

时间:2016-09-09 09:46:21

标签: java spring-boot

有没有办法在restTemplate.execute方法中设置httpEntiy?我必须将Authorization放在标题中,这就是为什么我不能排除它。作为ResponseEntity,我得到一个InputStreamResource。

没有HttpEntiy设置就可以了:

File responseFile = restTemplate.execute(
            uriComponents.toUri(), 
            HttpMethod.GET, null,
             new ResponseExtractor<File>() {
                @Override
                public File extractData(ClientHttpResponse response) throws IOException {

                    File serverFile = fileProcessHelper.createFile(pathToFile);
                    BufferedOutputStream stream = new BufferedOutputStream(
                            new FileOutputStream(serverFile));
                    byte[] bytes = IOUtils.toByteArray(response.getBody());
                    stream.write(bytes);
                    stream.close();

                  return serverFile;
                }
             });  

这不起作用。错误是:java.io.IOException:流已关闭

ResponseEntity<InputStreamResource> responseEntity = restTemplate.exchange(
                uriComponents.toUri(), 
                HttpMethod.GET, requestEntity, 
                InputStreamResource.class);


        InputStreamResource stream = new InputStreamResource(responseEntity.getBody().getInputStream());
        HttpHeaders respHeaders = new HttpHeaders();
        respHeaders.setContentLength(stream.contentLength());
        response.setHeader("Content-Disposition", "attachment; filename=" + stream.getFilename());

        return ResponseEntity.ok().headers(respHeaders).body(stream);

或者有没有办法重新打开inputstreamresource?

提前致谢!

1 个答案:

答案 0 :(得分:0)

确定。我找到了解决方案:

在RquestCallback中你可以设置标题:

RequestCallback requestCallback = new RequestCallback() {

    @Override
    public void doWithRequest(ClientHttpRequest request) throws IOException {      
            byte[] plainCredsBytes = plainCreds.getBytes();
            byte[] base64CredsBytes = Base64.encodeBase64(plainCredsBytes);
            String base64Creds = new String(base64CredsBytes);
            request.getHeaders().set("Authorization", "Basic " + base64Creds);
    }
};