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的消息发送。

  • 相关阅读:
    C#.net使用DotNetCharting控件生成报表统计图
    部署DTCMS到Jexus遇到的问题及解决思路--验证码
    部署DTCMS到Jexus遇到的问题及解决思路---部署
    LNMP环境搭建
    LAMP环境搭建
    Mac开发配置手册
    MAC OS X的命令行技巧
    如何生成SSH key
    ssh-keygen 的 详解
    Mac上Homebrew的使用——Homebrew 使 OS X 更完整
  • 原文地址:https://www.cnblogs.com/hx-web/p/13561657.html
Copyright © 2011-2022 走看看