美文网首页工作生活
使用restTemplate来进行服务器间的服务调用

使用restTemplate来进行服务器间的服务调用

作者: SmileMylife | 来源:发表于2019-07-01 17:05 被阅读0次

1.使用restTemplate进行服务调用。

@RequestMapping("/tesPicDownload")
    @ResponseBody
    public void testFileDownload() throws IOException {
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8);

        HttpEntity<Map<String, Object>> mapHttpEntity = new HttpEntity<>(new HashMap<>(), httpHeaders);

        RestTemplate restTemplate = new RestTemplate();
        byte[] stringResponseEntity = restTemplate.getForObject("http://127.0.0.1:8080/testForGong", byte[].class);
        FileCopyUtils.copy(stringResponseEntity, new FileOutputStream(new File("/Users/smile_mylife/Desktop/test.jpeg")));
        System.out.println(stringResponseEntity);
    }


    /**
     * 测试图片下载
     */
    @RequestMapping(value = "/testForGong", method = RequestMethod.GET)
    public void tesPicDownload(HttpServletResponse response) throws IOException {
        response.setHeader("content-type", MediaType.APPLICATION_OCTET_STREAM_VALUE);
        ServletOutputStream outputStream = response.getOutputStream();

        byte[] bytes = FileCopyUtils.copyToByteArray(new File("/Users/smile_mylife/Desktop/WechatIMG58.jpeg"));
        outputStream.write(bytes);
        outputStream.flush();
    }

以上代码为使用restTemplate进行服务器间的文件传输,首先testPicDownload使用restTemplate调用了testForGong的服务,然后该服务响应了一个二进制字节数组,然后请求端在接收的时候使用postForObject接收了一个byte[],至此请求端完整的接收了响应的文件。
以上内容适用任何文件的传输,当然如果上述响应的content-type替换为image-jpeg也可以通过这种形式进行接收,发起方应该使用getForObject然后使用二进制字节数组进行接收。

相关文章

网友评论

    本文标题:使用restTemplate来进行服务器间的服务调用

    本文链接:https://www.haomeiwen.com/subject/uvkncctx.html