欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

SpringBoot使用RestTemplate来调用接口

程序员文章站 2022-06-28 19:10:22
...
@RestController
public class DeptControllerConsumer {

    private static final String REST_URL_PREFIX = "http://localhost:8001";

    @Autowired
    private RestTemplate restTemplate;

    @RequestMapping(value="/consumer/dept/add")
    public boolean add(Dept dept)
    {
        return restTemplate.postForObject(REST_URL_PREFIX+"/dept/add", dept, Boolean.class);
    }

    @RequestMapping(value="/consumer/dept/get/{id}")
    public Dept get(@PathVariable("id") Long id)
    {
        return restTemplate.getForObject(REST_URL_PREFIX+"/dept/get/"+id, Dept.class);
    }

    @SuppressWarnings("unchecked")
    @RequestMapping(value="/consumer/dept/list")
    public List<Dept> list()
    {
        return restTemplate.getForObject(REST_URL_PREFIX+"/dept/list", List.class);
    }

}

// 使用restTemplate访问restful接口非常的简单粗暴无脑。
// (url, requestMap, ResponseBean.class)这三个参数分别代表 
// REST请求地址、请求参数、HTTP响应转换被转换成的对象类型。

  1. pom中要添加
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-web</artifactId>
</dependency>
  1. 启动类中添加
@Bean
	public RestTemplate getRestTemplate(){
		return new RestTemplate();
	}
	@Bean
	public ClientHttpRequestFactory simpleClientHttpRequestFactory() {
		SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
		factory.setReadTimeout(5000);//单位为ms
		factory.setConnectTimeout(5000);//单位为ms
		return factory;
	}
  1. 设置请求头的方式
//headers
HttpHeaders head = new HttpHeaders();
//设置数据传输格式
MediaType mediaType = MediaType.parseMediaType("application/json;charset=UTF-8 ");
head.setContentType(mediaType);
head.add("api-version", "1.0");
 //body
MultiValueMap<String, String> requestBody = new LinkedMultiValueMap<>();
requestBody.add("roundid", "1");
//HttpEntity
HttpEntity<MultiValueMap> requestEntity = new HttpEntity<MultiValueMap>(requestBody, head);
RestTemplate restTemplate = new RestTemplate();
//post
ResponseEntity<String> responseEntity = restTemplate.postForEntity("http://xxx", requestEntity, String.class);
System.out.println(responseEntity.getBody());