Spring RestTemplate 调用https

时间:2025-04-04 22:16:45
package com.fly.rest; import java.awt.image.BufferedImage; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Map; import javax.imageio.ImageIO; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.RandomUtils; import org.apache.commons.lang3.SystemUtils; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.FileSystemResource; 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.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; import org.springframework.web.client.RestTemplate; import com.fly.HttpBootApplication; import com.fly.core.utils.JsonBeanUtils; import com.fly.rest.bean.SearchReq; import lombok.extern.slf4j.Slf4j; /** * * RestTemplateTest * * @author 00fly * @version [版本号, 2018年11月6日] * @see [相关类/方法] * @since [产品/模块版本] */ @Slf4j @SpringBootTest(classes = HttpBootApplication.class) public class RestTemplateTest { @Autowired private RestTemplate restTemplate; @Test public void testDownLoadImg001() throws IOException { String downUrl = "/upload/2019/02/"; ResponseEntity<byte[]> responseEntity = restTemplate.getForEntity(downUrl, byte[].class); byte[] body = responseEntity.getBody(); // 数据落地 File dest = new File("upload/img_" + System.currentTimeMillis() + ".jpg"); dest.getParentFile().mkdirs(); try (FileOutputStream fos = new FileOutputStream(dest)) { fos.write(body); } if (SystemUtils.IS_OS_WINDOWS) { Runtime.getRuntime().exec("cmd /c start " + dest.getParentFile().getCanonicalPath()); } } @Test public void testDownLoadImg002() throws IOException { String downUrl = "/upload/2019/02/"; ResponseEntity<byte[]> responseEntity = restTemplate.getForEntity(downUrl, byte[].class); byte[] body = responseEntity.getBody(); File dest = new File("upload/img_" + System.currentTimeMillis() + ".jpg"); dest.getParentFile().mkdirs(); // 保存到本地 BufferedImage image = ImageIO.read(new ByteArrayInputStream(body)); ImageIO.write(image, "jpg", dest); if (SystemUtils.IS_OS_WINDOWS) { Runtime.getRuntime().exec("cmd /c start " + dest.getParentFile().getCanonicalPath()); } } @Test public void testExchange001() { String url = "/s"; HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON)); headers.add("token", "Bearer"); MultiValueMap<String, Object> params = new LinkedMultiValueMap<>(); params.add("type", 1); HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(params, headers); ResponseEntity<String> responseEntity; // GET with headers responseEntity = restTemplate.exchange(url, HttpMethod.GET, requestEntity, String.class); log.info("ResponseEntity={}", responseEntity); // POST responseEntity = restTemplate.exchange(url, HttpMethod.POST, requestEntity, String.class); log.info("ResponseEntity={}", responseEntity); } @Test public void testExchange002() { /**** url支持占位符 ****/ String url = "http://localhost:8080/rest/user/list/{page}"; HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON)); MultiValueMap<String, String> params = new LinkedMultiValueMap<>(); params.add("username", "用户1"); params.add("password", "123456"); HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(params, headers); ResponseEntity<String> responseEntity; // GET、POST responseEntity = restTemplate.exchange(url, HttpMethod.GET, requestEntity, String.class, 1); log.info("ResponseEntity={}", responseEntity); Map<String, Integer> vars = Collections.singletonMap("page", 1); responseEntity = restTemplate.exchange(url, HttpMethod.POST, requestEntity, String.class, vars); log.info("ResponseEntity={}", responseEntity); } @Test public void testFormData001() { // POST请求只能用MultiValueMap String url = "/post"; HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON)); MultiValueMap<String, String> params = new LinkedMultiValueMap<>(); params.add("q1", "java"); params.add("q2", "python"); HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(params, headers); if (RandomUtils.nextBoolean()) { String response = restTemplate.postForObject(url, requestEntity, String.class); log.info("ResponseBody={}", response); } else { ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, requestEntity, String.class); log.info("ResponseEntity={}", responseEntity.getBody()); } } @Test public void testFormData002() { /**** url支持占位符 ****/ String url = "http://localhost:8080/rest/user/list/{page}"; HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); MultiValueMap<String, String> params = new LinkedMultiValueMap<>(); params.add("username", "user001"); params.add("password", "123456"); HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(params, headers); ResponseEntity<String> responseEntity; String response = restTemplate.postForObject(url, requestEntity, String.class, 1); log.info("ResponseBody={}", response); responseEntity = restTemplate.postForEntity(url, requestEntity, String.class, 1); log.info("ResponseEntity={}", responseEntity); } @Test public void testGet001() { /**** url支持占位符 ****/ String url = "http://localhost:8080/rest/user/list/{page}"; String response = restTemplate.getForObject(url, String.class, 1); log.info("ResponseBody={}", response); ResponseEntity<String> responseEntity = restTemplate.getForEntity(url, String.class, 1); log.info("ResponseEntity={}", responseEntity); } @Test public void testGet002() { String url = "/get"; ResponseEntity<String> responseEntity = restTemplate.getForEntity(url, String.class); log.info("ResponseEntity StatusCode={}", responseEntity.getStatusCode()); log.info("ResponseEntity={}", responseEntity); } @Test public void testGet003() { String url = "/get"; String responseBody = restTemplate.getForObject(url, String.class); log.info("responseBody={}", responseBody); } /** * RestTemplateConfig需引入HttpComponentsClientRestfulHttpRequestFactory支持GET请求携带body数据 * * @throws IOException */ @Test public void testGetWithBody() throws IOException { String url = "http://127.0.0.1:9380/v1/tracking/component/output/data/download"; HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON)); // 必须用HashMap? Map<String, String> params = new HashMap<>(); params.put("job_id", ""); params.put("role", "guest"); params.put("party_id", "10000"); params.put("component_name", "intersect_0"); HttpEntity<Map<String, String>> requestEntity = new HttpEntity<>(params, headers); // 支持GET请求携带body数据 ResponseEntity<byte[]> responseEntity = restTemplate.exchange(url, HttpMethod.GET, requestEntity, byte[].class); byte[] bytes = responseEntity.getBody(); File dest = new File("download/"); dest.getParentFile().mkdirs(); try (OutputStream fos = new FileOutputStream(dest)) { fos.write(bytes); } } /** * 演示@RequestBody请求 * * @throws IOException */ @Test public void testJsonRequestBody() throws IOException { String url = "/post"; HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON)); Map<String, String> map = new HashMap<>(); ResponseEntity<String> responseEntity; int num = RandomUtils.nextInt(1, 4); switch (num) { case 1: // 方式1,javaBean SearchReq req = new SearchReq(); req.setPageNo(1); req.setPageSize(5); req.setKeyword("0"); responseEntity = restTemplate.postForEntity(url, new HttpEntity<>(req, headers), String.class); log.info("ResponseEntity = {}", responseEntity); break; case 2: // 方式2,HashMap map.clear(); map.put("pageNo", "2"); map.put("pageSize", "10"); map.put("keyword", "1"); responseEntity = restTemplate.postForEntity(url, new HttpEntity<>(map, headers), String.class); log.info("ResponseEntity={}", responseEntity); break; case 3: // 方式3,Json字符串 map.clear(); map.put("pageNo", "3"); map.put("pageSize", "15"); map.put("keyword", "2"); responseEntity = restTemplate.postForEntity(url, new HttpEntity<>(JsonBeanUtils.beanToJson(map, false), headers), String.class); log.info("ResponseEntity={}", responseEntity); break; } } @Test public void testPost001() { String url = "/"; HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(headers); String responseBody = restTemplate.postForObject(url, requestEntity, String.class); log.info("responseBody={}", responseBody); } @Test public void testPost002() { // POST请求只能用MultiValueMap String url = "/post"; HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON)); MultiValueMap<String, String> params = new LinkedMultiValueMap<>(); params.add("id", "123456"); HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(params, headers); ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, requestEntity, String.class); log.info("ResponseEntity={}", responseEntity); } @Test public void testUpload001() throws IOException { // POST请求只能用MultiValueMap String url = "/post"; HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.MULTIPART_FORM_DATA); headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON)); // 注意:FileSystemResource只适用于文件,Jar內运行报错 MultiValueMap<String, Object> params = new LinkedMultiValueMap<>(); String path = new ClassPathResource("").getURL().getPath(); log.info(path); FileSystemResource file = new FileSystemResource(path); // 多次调用,后台接受到的是MultipartFile[] params.add("file", file); params.add("file", file); params.add("file", file); params.add("name", "girl"); params.add("age", "18"); HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(params, headers); ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, requestEntity, String.class); log.info("ResponseEntity={}", responseEntity); } @Test public void testUpload002() { // POST请求只能用MultiValueMap String url = "/post"; HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.MULTIPART_FORM_DATA); headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON)); // Resource适用于文件、Jar內 MultiValueMap<String, Object> params = new LinkedMultiValueMap<>(); Resource file = new ClassPathResource(""); // 多次调用,后台接受到的是MultipartFile[] params.add("file", file); params.add("file", file); params.add("file", file); params.add("name", "girl"); params.add("age", "18"); HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(params, headers); ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, requestEntity, String.class); log.info("ResponseEntity={}", responseEntity); } @Test public void testWebService() throws IOException { String url = "http://127.0.0.1:7879/demo/services/ws_inputService"; HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.TEXT_XML); headers.setAccept(Arrays.asList(MediaType.TEXT_XML)); InputStream is = this.getClass().getResourceAsStream("/request"); String requestString = IOUtils.toString(is, StandardCharsets.UTF_8); HttpEntity<String> requestEntity = new HttpEntity<>(requestString, headers); ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, requestEntity, String.class); log.info("ResponseEntity Body = {}", responseEntity.getBody()); } }