RestTemplate的使用

男娘i 2022-12-05 15:19 224阅读 0赞

RestTemplate,用于调用远程服务

导入依赖:

RestTemplate是spring的一个rest客户端,在spring-web这个包下,spring boot的依赖

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-web</artifactId>
  4. </dependency>

在controller里面注入:

  1. @Autowired
  2. private RestTemplate restTemplate;

具体代码实现demo:

  1. @PostMapping("sdqj/djk")
  2. public ResponseResult confirm_alarm(@RequestBody confirm_alrmVO vo) {
  3. Map<String, Object> param = new HashMap();
  4. //使用String.join方法截取传过来的字符串数组,用“,”分隔
  5. String ids = String.join(",", vo.getObj_ids());
  6. System.out.println(ids);
  7. param.put("obj_ids", ids);
  8. param.put("scfl", vo.getScfl().toString());
  9. //设置请求头类型
  10. HttpHeaders httpHeaders = new HttpHeaders();
  11. httpHeaders.setContentType(MediaType.APPLICATION_JSON);
  12. //传参数,请求体和请求头放在requestEntity
  13. HttpEntity<Map> requestEntity = new HttpEntity<>(param,httpHeaders);
  14. //post请求,调用远程
  15. JSONObject jsonObject = restTemplate.postForObject(
  16. "http://localhost:31230/sdqj/online_monitor/confirm_alarm", requestEntity, JSONObject.class);
  17. return ResponseResult.success();
  18. }

引入的包:

  1. import java.util.HashMap;
  2. import java.util.Map;
  3. import org.springframework.beans.factory.annotation.Autowired;
  4. import org.springframework.http.HttpEntity;
  5. import org.springframework.http.HttpHeaders;
  6. import org.springframework.http.MediaType;
  7. import org.springframework.web.bind.annotation.PostMapping;
  8. import org.springframework.web.bind.annotation.RequestBody;
  9. import org.springframework.web.bind.annotation.RestController;
  10. import org.springframework.web.client.RestTemplate;
  11. import com.alibaba.fastjson.JSONObject;
  12. import com.whayer.sdqj.monitorMom.domain.ResponseResult;
  13. import com.whayer.sdqj.monitorMom.vo.confirm_alrmVO;

只是自己简单的总结!!!!

发表评论

表情:
评论列表 (有 0 条评论,224人围观)

还没有评论,来说两句吧...

相关阅读

    相关 restTemplate使用

    目录 目录 一、概述? 二、使用步骤 1.引入依赖 2.创建RestTemplate对象,交由spring容器进行管理 3.使用方法 3.1 GET请求