(一)配置类
package com.vincent.demo.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.client.ClientHttpRequestFactory; import org.springframework.http.client.SimpleClientHttpRequestFactory; import org.springframework.web.client.RestTemplate; @Configuration public class RestTemplateConfig { @Bean public RestTemplate restTemplate(ClientHttpRequestFactory factory) { return new RestTemplate(factory); } @Bean public ClientHttpRequestFactory simpleClientHttpRequestFactory() { SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory(); factory.setReadTimeout(5000); factory.setConnectTimeout(15000); return factory; } }
(二)rest接口的controller
package com.vincent.demo.controller; import com.alibaba.fastjson.JSONObject; import com.vincent.demo.vo.TestVO; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; /** * @author rw * @date 2019/1/9 下午1:03 */ @RestController public class RestTestController { @GetMapping("/getTest") public String getTest() { return "getTest"; } @GetMapping("/getObjectTest") public TestVO getObjectTest() { TestVO testVO = new TestVO(); testVO.setId(1L); testVO.setName("test"); return testVO; } @DeleteMapping("/deleteEntityTest") public JSONObject deleteEntityTest(@RequestParam Long id) { JSONObject jsonObject = new JSONObject(); jsonObject.put("id", id); return jsonObject; } }
(三)测试
@Autowired RestTemplate restTemplate; @Test public void getTest() throws URISyntaxException { String msg = restTemplate.getForObject("http://localhost:8080/getTest", String.class); System.out.println(msg); ResponseEntity<String> entity = restTemplate.getForEntity("http://localhost:8080/getTest", String.class); System.out.println("body:" + entity.getBody() + ",StatusCode:" + entity.getStatusCode() + ",StatusCodeValue:" + entity.getStatusCodeValue() + ",:Headers" + entity.getHeaders()); //使用RequestEntity的一个弊端是new URI()要处理URISyntaxException RequestEntity requestEntity = RequestEntity.get(new URI("http://localhost:8080/getTest")).build(); restTemplate.exchange(requestEntity, String.class); ResponseEntity<String> entity1 = restTemplate.exchange("http://localhost:8080/getTest", HttpMethod.GET, null, String.class); ResponseEntity<TestVO> entity2 = restTemplate.exchange("http://localhost:8080/getObjectTest", HttpMethod.GET, null, TestVO.class); System.out.println("body:" + entity2.getBody() + ",StatusCode:" + entity2.getStatusCode() + ",StatusCodeValue:" + entity2.getStatusCodeValue() + ",:Headers" + entity2.getHeaders()); }
(四)总结
原文地址:https://www.cnblogs.com/vincentren/p/10247146.html
时间: 2024-11-25 18:24:26