spring boot resttemplate下载文件

spring boot resttemplate下载文件

package ess.api;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class GetAPI {

    private TestRestTemplate template = null;

    @Before
    public void testBefore() {
        template = new TestRestTemplate();
    }

    @Test
    public void testGet() {
        HttpHeaders headers = new HttpHeaders();
        HttpEntity httpEntity = new HttpEntity(headers);
        ResponseEntity response = template.exchange("http://img.blog.csdn.net/20161109183525859", HttpMethod.GET,
                httpEntity, byte[].class);
        log.info("===状态码================");
        log.info(">> {}", response.getStatusCodeValue());
        log.info("===返回信息================");
        log.info(">> {}", response.getHeaders().getContentType());
        log.info(">> {}", response.getHeaders().getContentType().getSubtype());
        try {
            File file = File.createTempFile("ess-", "." + response.getHeaders().getContentType().getSubtype());
            FileOutputStream fos = new FileOutputStream(file);
            fos.write(response.getBody());
            fos.flush();
            fos.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    @After
    public void testAfter() {
        template = null;
    }

}

==手机QQ扫描下方二维码,快速加入Java架构师交流群==

spring boot resttemplate下载文件_第1张图片
image

你可能感兴趣的:(spring boot resttemplate下载文件)