springboot學習總結(三)RestTemplate用法
阿新 • • 發佈:2019-01-10
ota adt ons .get bject 學習總結 mapping entity The
(一)配置類
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; @Configurationpublic class RestTemplateConfig { @Bean public RestTemplate restTemplate(ClientHttpRequestFactory factory) { return new RestTemplate(factory); } @Bean public ClientHttpRequestFactory simpleClientHttpRequestFactory() { SimpleClientHttpRequestFactory factory = newSimpleClientHttpRequestFactory(); 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()); }
(四)總結
springboot學習總結(三)RestTemplate用法