├── .gitignore ├── README.md ├── pom.xml └── src ├── main ├── java │ └── com │ │ └── one │ │ └── learn │ │ └── resttemplate │ │ ├── ResttemplateApplication.java │ │ ├── bean │ │ └── Product.java │ │ └── controller │ │ └── ProductController.java └── resources │ └── application.properties └── test └── java └── com └── one └── learn └── resttemplate ├── RestTemplateTests.java └── ResttemplateApplicationTests.java /.gitignore: -------------------------------------------------------------------------------- 1 | HELP.md 2 | /target/ 3 | !.mvn/wrapper/maven-wrapper.jar 4 | 5 | ### STS ### 6 | .apt_generated 7 | .classpath 8 | .factorypath 9 | .project 10 | .settings 11 | .springBeans 12 | .sts4-cache 13 | 14 | ### IntelliJ IDEA ### 15 | .idea 16 | *.iws 17 | *.iml 18 | *.ipr 19 | 20 | ### NetBeans ### 21 | /nbproject/private/ 22 | /nbbuild/ 23 | /dist/ 24 | /nbdist/ 25 | /.nb-gradle/ 26 | /build/ 27 | 28 | ### VS Code ### 29 | .vscode/ 30 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # resttemplate 2 | [《一起学 Spring 之 RestTemplate 使用指南 》](https://wrcj12138aaa.github.io/2019/05/11/%E4%B8%80%E8%B5%B7%E5%AD%A6%20Spring%20%E4%B9%8B%20RestTemplate/) 一文的演示 Demo 3 | 4 | # 参考资料 5 | http://blog.didispace.com/spring-boot-learning-21-1-1 6 | 7 | https://start.spring.io "Spring Initializr" 8 | 9 | https://www.baeldung.com/rest-template 10 | 11 | https://www.baeldung.com/spring-rest-template-multipart-upload 12 | 13 | https://howtodoinjava.com/spring-boot2/resttemplate-timeout-example/ "resttemplate-timeout-example" 14 | 15 | https://howtodoinjava.com/spring-restful/resttemplate-httpclient-java-config/ "resttemplate-httpclient-java-config" 16 | 17 | https://netty.io/ "Netty" 18 | 19 | https://square.github.io/okhttp "OkHttp" 20 | 21 | https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/client/RestTemplate.html "resttemplate javadoc" 22 | 23 | https://docs.spring.io/spring/docs/5.1.6.RELEASE/spring-framework-reference/integration.html#rest-client-access "rest-client-access" 24 | 25 | https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/client/RestOperations.html "restoperation javadoc" 26 | 27 | 28 | 29 | 30 | 31 | 32 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | org.springframework.boot 7 | spring-boot-starter-parent 8 | 2.1.4.RELEASE 9 | 10 | 11 | com.one.learn 12 | resttemplate 13 | 0.0.1-SNAPSHOT 14 | resttemplate 15 | Demo project for Spring Boot 16 | 17 | 18 | 1.8 19 | 20 | 21 | 22 | 23 | org.springframework.boot 24 | spring-boot-starter-web 25 | 26 | 27 | 28 | org.springframework.boot 29 | spring-boot-starter-test 30 | test 31 | 32 | 33 | 34 | 35 | 36 | 37 | org.springframework.boot 38 | spring-boot-maven-plugin 39 | 40 | 41 | 42 | 43 | 44 | -------------------------------------------------------------------------------- /src/main/java/com/one/learn/resttemplate/ResttemplateApplication.java: -------------------------------------------------------------------------------- 1 | package com.one.learn.resttemplate; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | /** 7 | * @author One 8 | */ 9 | @SpringBootApplication 10 | public class ResttemplateApplication { 11 | 12 | public static void main(String[] args) { 13 | SpringApplication.run(ResttemplateApplication.class, args); 14 | } 15 | 16 | } 17 | -------------------------------------------------------------------------------- /src/main/java/com/one/learn/resttemplate/bean/Product.java: -------------------------------------------------------------------------------- 1 | package com.one.learn.resttemplate.bean; 2 | 3 | import java.math.BigDecimal; 4 | 5 | /** 6 | * @author One 7 | * @description 产品 8 | * @date 2019/05/07 9 | */ 10 | public class Product { 11 | private Integer id; 12 | private String name; 13 | private BigDecimal price; 14 | 15 | public Product() { 16 | } 17 | 18 | public Product(Integer id, String name, BigDecimal price) { 19 | this.id = id; 20 | this.name = name; 21 | this.price = price; 22 | } 23 | 24 | public Integer getId() { 25 | return id; 26 | } 27 | 28 | public void setId(Integer id) { 29 | this.id = id; 30 | } 31 | 32 | public String getName() { 33 | return name; 34 | } 35 | 36 | public void setName(String name) { 37 | this.name = name; 38 | } 39 | 40 | public BigDecimal getPrice() { 41 | return price; 42 | } 43 | 44 | public void setPrice(BigDecimal price) { 45 | this.price = price; 46 | } 47 | 48 | @Override 49 | public String toString() { 50 | return "Product{" + 51 | "id='" + id + '\'' + 52 | ", name='" + name + '\'' + 53 | ", price='" + price + '\'' + 54 | '}'; 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /src/main/java/com/one/learn/resttemplate/controller/ProductController.java: -------------------------------------------------------------------------------- 1 | package com.one.learn.resttemplate.controller; 2 | 3 | import com.one.learn.resttemplate.bean.Product; 4 | import org.springframework.web.bind.annotation.*; 5 | import org.springframework.web.multipart.MultipartFile; 6 | import org.springframework.web.multipart.MultipartRequest; 7 | 8 | import java.math.BigDecimal; 9 | 10 | /** 11 | * @author One 12 | * @Description Product 控制器 13 | */ 14 | @RequestMapping("/product") 15 | @RestController 16 | public class ProductController { 17 | 18 | @GetMapping("/get_product1") 19 | public Product get_product1() { 20 | return new Product(1, "ProductA", BigDecimal.valueOf(6666.0)); 21 | } 22 | 23 | @GetMapping("/get_product2") 24 | public Product get_product2(Integer id) { 25 | return new Product(id, "ProductC", BigDecimal.valueOf(6666.0)); 26 | } 27 | 28 | @GetMapping("/get_product3") 29 | public String get_product3(Product product) { 30 | return product.toString(); 31 | } 32 | 33 | 34 | @PostMapping("/post_product1") 35 | public String post_product1(Product product) { 36 | return product.toString(); 37 | } 38 | 39 | @PostMapping("/post_product2") 40 | public String post_product2(@RequestBody Product product) { 41 | return product.toString(); 42 | } 43 | 44 | @DeleteMapping("/delete/{id}") 45 | public String delete(@PathVariable Integer id) { 46 | String result = String.format("编号为%s的产品删除成功", id); 47 | System.out.println(result); 48 | return result; 49 | } 50 | 51 | @PutMapping("/update") 52 | public String updateByPut(Product product) { 53 | String result = product.toString() + " 更新成功"; 54 | System.out.println(result); 55 | return result; 56 | } 57 | 58 | @PostMapping("/upload") 59 | public String upload(MultipartRequest request) { 60 | MultipartFile file = request.getFile("file"); 61 | String originalFilename = file.getOriginalFilename(); 62 | return "upload success filename: " + originalFilename; 63 | } 64 | } -------------------------------------------------------------------------------- /src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /src/test/java/com/one/learn/resttemplate/RestTemplateTests.java: -------------------------------------------------------------------------------- 1 | package com.one.learn.resttemplate; 2 | 3 | import com.one.learn.resttemplate.bean.Product; 4 | import org.junit.Before; 5 | import org.junit.Test; 6 | import org.springframework.core.io.FileSystemResource; 7 | import org.springframework.http.*; 8 | import org.springframework.http.client.SimpleClientHttpRequestFactory; 9 | import org.springframework.util.Assert; 10 | import org.springframework.util.LinkedMultiValueMap; 11 | import org.springframework.util.MultiValueMap; 12 | import org.springframework.web.client.RestTemplate; 13 | 14 | import java.io.File; 15 | import java.io.InputStream; 16 | import java.math.BigDecimal; 17 | import java.util.Arrays; 18 | import java.util.HashMap; 19 | import java.util.Map; 20 | 21 | import static org.springframework.util.Assert.isTrue; 22 | 23 | /** 24 | * @author One 25 | * @Description RestTemplate 请求测试类 26 | * @date 2019/05/09 27 | */ 28 | public class RestTemplateTests { 29 | RestTemplate restTemplate = new RestTemplate(); 30 | RestTemplate customRestTemplate = null; 31 | 32 | @Before 33 | public void setup() { 34 | customRestTemplate = new RestTemplate(getClientHttpRequestFactory()); 35 | } 36 | 37 | private SimpleClientHttpRequestFactory getClientHttpRequestFactory() { 38 | SimpleClientHttpRequestFactory clientHttpRequestFactory 39 | = new SimpleClientHttpRequestFactory(); 40 | // 连接超时设置 10s 41 | clientHttpRequestFactory.setConnectTimeout(10_000); 42 | 43 | // 读取超时设置 10s 44 | clientHttpRequestFactory.setReadTimeout(10_000); 45 | return clientHttpRequestFactory; 46 | } 47 | 48 | @Test 49 | public void testGet_product1() { 50 | String url = "http://localhost:8080/product/get_product1"; 51 | String result = restTemplate.getForObject(url, String.class); 52 | System.out.println("get_product1返回结果:" + result); 53 | Assert.hasText(result, "get_product1返回结果为空"); 54 | 55 | Product product = restTemplate.getForObject(url, Product.class); 56 | System.out.println("get_product1返回结果:" + product); 57 | Assert.notNull(product, "get_product1返回结果为空"); 58 | 59 | ResponseEntity responseEntity = restTemplate.getForEntity(url, Product.class); 60 | System.out.println("get_product1返回结果:" + responseEntity); 61 | Assert.isTrue(responseEntity.getStatusCode().equals(HttpStatus.OK), "get_product1响应不成功"); 62 | 63 | MultiValueMap header = new LinkedMultiValueMap(); 64 | header.add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE); 65 | HttpEntity requestEntity = new HttpEntity<>(header); 66 | ResponseEntity exchangeResult = restTemplate.exchange(url, HttpMethod.GET, requestEntity, Product.class); 67 | System.out.println("get_product1返回结果:" + exchangeResult); 68 | Assert.isTrue(exchangeResult.getStatusCode().equals(HttpStatus.OK), "get_product1响应不成功"); 69 | 70 | String executeResult = restTemplate.execute(url, HttpMethod.GET, request -> { 71 | request.getHeaders().add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE); 72 | }, (clientHttpResponse) -> { 73 | InputStream body = clientHttpResponse.getBody(); 74 | byte[] bytes = new byte[body.available()]; 75 | body.read(bytes); 76 | return new String(bytes); 77 | }); 78 | System.out.println("get_product1返回结果:" + executeResult); 79 | Assert.hasText(executeResult, "get_product1返回结果为空"); 80 | } 81 | 82 | @Test 83 | public void testGet_product2() { 84 | String url = "http://localhost:8080/product/get_product2?id={id}"; 85 | ResponseEntity responseEntity = restTemplate.getForEntity(url, Product.class, 101); 86 | System.out.println(responseEntity); 87 | isTrue(responseEntity.getStatusCode().equals(HttpStatus.OK), "get_product2 请求不成功"); 88 | Assert.notNull(responseEntity.getBody().getId(), "get_product2 传递参数不成功"); 89 | 90 | Map uriVariables = new HashMap<>(); 91 | uriVariables.put("id", 101); 92 | Product result = restTemplate.getForObject(url, Product.class, uriVariables); 93 | System.out.println(result); 94 | Assert.notNull(result.getId(), "get_product2 传递参数不成功"); 95 | } 96 | 97 | @Test 98 | public void testPost_product1() { 99 | String url = "http://localhost:8080/product/post_product1"; 100 | MultiValueMap header = new LinkedMultiValueMap(); 101 | header.add(HttpHeaders.CONTENT_TYPE, (MediaType.APPLICATION_FORM_URLENCODED_VALUE)); 102 | Product product = new Product(201, "Macbook", BigDecimal.valueOf(10000)); 103 | String productStr = "id=" + product.getId() + "&name=" + product.getName() + "&price=" + product.getPrice(); 104 | HttpEntity request = new HttpEntity<>(productStr, header); 105 | ResponseEntity exchangeResult = restTemplate.exchange(url, HttpMethod.POST, request, String.class); 106 | System.out.println("post_product1: " + exchangeResult); 107 | Assert.isTrue(exchangeResult.getStatusCode().equals(HttpStatus.OK), "post_product1 请求不成功"); 108 | 109 | MultiValueMap map = new LinkedMultiValueMap(); 110 | map.add("id", (product.getId())); 111 | map.add("name", (product.getName())); 112 | map.add("price", (product.getPrice())); 113 | HttpEntity request2 = new HttpEntity<>(map, header); 114 | ResponseEntity exchangeResult2 = restTemplate.exchange(url, HttpMethod.POST, request2, String.class); 115 | System.out.println("post_product1: " + exchangeResult2); 116 | Assert.isTrue(exchangeResult.getStatusCode().equals(HttpStatus.OK), "post_product1 请求不成功"); 117 | } 118 | 119 | @Test 120 | public void testPost_product2() { 121 | String url = "http://localhost:8080/product/post_product2"; 122 | MultiValueMap header = new LinkedMultiValueMap(); 123 | header.put(HttpHeaders.CONTENT_TYPE, Arrays.asList(MediaType.APPLICATION_JSON_VALUE)); 124 | header.put(HttpHeaders.ACCEPT, Arrays.asList(MediaType.APPLICATION_JSON_VALUE)); 125 | HttpEntity request = new HttpEntity<>(new Product(2, "Macbook", BigDecimal.valueOf(10000)), header); 126 | ResponseEntity exchangeResult = restTemplate.exchange(url, HttpMethod.POST, request, String.class); 127 | System.out.println("post_product2: " + exchangeResult); 128 | Assert.isTrue(exchangeResult.getStatusCode().equals(HttpStatus.OK), "post_product2 请求不成功"); 129 | } 130 | 131 | @Test 132 | public void testDelete() { 133 | String url = "http://localhost:8080/product/delete/{id}"; 134 | restTemplate.delete(url, 101); 135 | } 136 | 137 | @Test 138 | public void testPut() { 139 | String url = "http://localhost:8080/product/update"; 140 | Map variables = new HashMap<>(); 141 | MultiValueMap header = new LinkedMultiValueMap(); 142 | header.put(HttpHeaders.CONTENT_TYPE, Arrays.asList(MediaType.APPLICATION_FORM_URLENCODED_VALUE)); 143 | Product product = new Product(101, "iWatch", BigDecimal.valueOf(2333)); 144 | String productStr = "id=" + product.getId() + "&name=" + product.getName() + "&price=" + product.getPrice(); 145 | HttpEntity request = new HttpEntity<>(productStr, header); 146 | restTemplate.put(url, request); 147 | } 148 | 149 | @Test 150 | public void testUploadFile() { 151 | String url = "http://localhost:8080/product/upload"; 152 | MultiValueMap body = new LinkedMultiValueMap<>(); 153 | Object file = new FileSystemResource(new File("/Users/One/Desktop/b.txt")); 154 | body.add("file", file); 155 | 156 | MultiValueMap header = new LinkedMultiValueMap(); 157 | header.put(HttpHeaders.CONTENT_TYPE, Arrays.asList(MediaType.MULTIPART_FORM_DATA_VALUE)); 158 | HttpEntity> requestEntity = new HttpEntity<>(body, header); 159 | ResponseEntity responseEntity = restTemplate.postForEntity(url, requestEntity, String.class); 160 | System.out.println("upload: " + responseEntity); 161 | Assert.isTrue(responseEntity.getStatusCode().equals(HttpStatus.OK), "upload 请求不成功"); 162 | } 163 | 164 | } 165 | -------------------------------------------------------------------------------- /src/test/java/com/one/learn/resttemplate/ResttemplateApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.one.learn.resttemplate; 2 | 3 | public class ResttemplateApplicationTests { 4 | 5 | } 6 | --------------------------------------------------------------------------------