zoukankan      html  css  js  c++  java
  • 浅谈springboot 中如何通过restTemplate发送带有header和token的网络请求

    最近在进行第三方接口对接,在对接过程中要用到大量的restTemplate的使用,个人觉得restTemplate装载带token的header发送网络请求是很重要的一个知识点,我在这里简单记录下:

    第一步,注入TestRestTemplate:

      @Autowired
        private TestRestTemplate testRestTemplate;
        private RestTemplate restTemplate;
    

      

    第二步,初始化restTemplate:
      restTemplate = testRestTemplate.getRestTemplate();
    

     第三步,填充header,将token信息和content-type写入header中,没有content-type读取时是也会报错的:

     HttpHeaders headers = new HttpHeaders();
     headers.add("Authorization", stringRedisTemplate.opsForValue().get("token"));
    headers.add("Content-Type", "application/json");

    第四步,填装数据,这里的数据用json的方式发送,也可以用其它方式,比如string:

    JSONObject para = new JSONObject();
            para.put("StartTime", param.get("startTime"));
            para.put("EndTime", param.get("endTime"));
            para.put("AlarmType", param.get("alarmType"));
            para.put("AlarmDesc", param.get("alarmDesc"));
            para.put("QueryType", param.get("queryType"));
            para.put("QueryKey", param.get("queryKey"));di
    

    第五步,发送请求给第三方并获得数据:

      HttpEntity<String> formEntity = new HttpEntity<String>(para.toJSONString(), headers);
            ResponseEntity<String> response = restTemplate.exchange(
                URL,//获取资源的地址
                HttpMethod.POST,
                formEntity,
                String.class//返回类型设为String
            );
            String body = response.getBody();
    

      这样就实现了带header的消息发送。

  • 相关阅读:
    Scrapy爬虫之from import错误解决
    Mysql之IF嵌套和CASE WHEN的转化
    win10安装Redis
    win10安装elasticsearch
    Flink输出到JDBC
    Flink输出到Elasticsearch
    Flink输出到Redis
    IntelliJ IDEA 激活—2020年1月10号
    Flink输出到Kafka(两种方式)
    用C写一个功能较为完善的贪吃蛇小游戏
  • 原文地址:https://www.cnblogs.com/hx-web/p/13561657.html
Copyright © 2011-2022 走看看