RestTemplate 配置及使用

介绍

RestTemplate 是从 Spring3.0 开始支持的一个 HTTP 请求工具,它提供了常见的REST请求方案的模版,例如 GET 请求、POST 请求、PUT 请求、DELETE 请求以及一些通用的请求执行方法 exchange 以及 execute。RestTemplate 继承自 InterceptingHttpAccessor 并且实现了 RestOperations 接口,其中 RestOperations 接口定义了基本的 RESTful 操作,这些操作在 RestTemplate 中都得到了实现。本文主要讲解其它两种配置及使用

配置及使用

  1. 配置

RestTemplateConfig.java

@Configuration
public class RestTemplateConfig {
	/**
	 内部请求模板
	*/
    @LoadBalanced
    @Bean(value = {"restTemplateFeign"})
    public RestTemplate restTemplateFeign() {
        return new RestTemplate();
    }
	/**
	 普通请求模板
	*/
    @Bean(value = {"restTemplate"})
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }
}

RestTemplateConfig.java 中配置了两个请求模板,restTemplateFeign配置的是负载均衡的内部请求模板,restTemplate配置为通用的请求模板。

  1. 使用
    restTemplateFeign 的使用
    内部调用部分代码
 @Autowired
 private RestTemplate restTemplateFeign;

//内部url
String INNER_URL = "http://xxxfile/identity/factorAuth";
//三要素认证2
    private boolean factorAuth0(String name, String idcard, String mobile){
        if (StringUtils.isEmpty(name)) {
            throw new CustomException("三要素认证,用户姓名不能为空");
        }
        if (StringUtils.isEmpty(idcard)) {
            throw new CustomException("三要素认证,身份证号码不能为空");
        }
        if (StringUtils.isEmpty(mobile)) {
            throw new CustomException("三要素认证,手机号不能为空");
        }
        //是否开启三要素认证
        SysConfig config = new SysConfig();
        config.setConfigKey("open.factor.auth");
        SysConfig retConfig = configMapper.selectConfig(config);
        String openAuth = retConfig.getConfigValue();
        if("0".equals(openAuth)){
            return true;
        }
        boolean authResult = false;
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("name",name);
        jsonObject.put("idcard", idcard);
        jsonObject.put("mobile", mobile);
        log.info("开始三要素认证,请求参数:" + jsonObject);
        AjaxResult ajaxResult = null;
        try{
            ajaxResult = restTemplateFeign.postForObject(INNER_URL,jsonObject,AjaxResult.class);
            log.info("结束三要素认证,返回参数:" + ajaxResult);
            if(ajaxResult != null){
                if("200".equals(String.valueOf(ajaxResult.get("code")))){
                    JSONObject data = JSONObject.parseObject(JSON.toJSONString(ajaxResult.get("data")));
                    Integer status = (Integer)data.get("status");
                    if(status != null && status != 1){
                        throw new CustomException((String)data.get("errReason"));
                    }
                    if(status == null){
                        throw new CustomException("三要素认证失败");
                    }
                    authResult = true;
                } else {
                    throw new CustomException(String.valueOf(ajaxResult.get("msg")), (int)(ajaxResult.get("code")));
                }
            }
        } catch (Exception e) {
            log.error("三要素认证,异常信息:" + e);
            if(e instanceof CustomException){
                throw new CustomException(e.getMessage(),((CustomException) e).getCode());
            }
            throw new CustomException("三要素认证失败,请稍后重试");
        }
        return authResult;
    }

外部调用部分代码

 @Autowired
 private RestTemplate restTemplate;
 String OUT_URL= https://ydoa.gzairports.com/login
    @Override
    public JSONObject ssoLogin(String ticket) {
        log.info("致信xxx调用登录ticket:{}", ticket);
        String url = seeyonUrl + ticket;
        log.info("致信xxx调用登录url:{}", OUT_URL);
        String reson = restTemplate.getForObject(OUT_URL, String.class);
        log.info("致信xxx调用成功参数:{}", reson);
        if(org.springframework.util.StringUtils.isEmpty(reson)){
            throw new CustomException("用户不存在!");
        }
        String[] split = reson.split("\n");
        JSONObject jsonObject = ssoLoginByUserCode(split[0]);
        return jsonObject;
    }

总结

如果使用负载均衡模板去请求外部url会报错,找到对应的服务,这个问题在注入模板时的变量名要和配置时候保持一致。

  • 10
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot RestTemplate 是一个 HTTP 客户端库,用于向 RESTful API 发送请求和接收响应。它可以与大多数 HTTP 请求和响应库一起使用,如 Apache HttpClient、OkHttp 等。 以下是 Spring Boot RestTemplate配置使用步骤: 1. 引入 RestTemplate 依赖 在 Spring Boot 项目的 pom.xml 文件中添加以下依赖: ``` <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web-services</artifactId> </dependency> ``` 这些依赖包含了 RestTemplate 所需的所有类和配置。 2. 创建 RestTemplate Bean 在 Spring Boot 中,可以使用 @Bean 注解创建 RestTemplate Bean。在创建 RestTemplate Bean 时,可以配置一些属性,如连接超时时间、读取超时时间等。 以下是一个基本的 RestTemplate 配置: ``` @Configuration public class RestTemplateConfig { @Bean public RestTemplate restTemplate() { return new RestTemplateBuilder() .setConnectTimeout(Duration.ofSeconds(10)) .setReadTimeout(Duration.ofSeconds(10)) .build(); } } ``` 3. 发送 GET 请求 使用 RestTemplate 发送 GET 请求的示例代码如下: ``` @Autowired private RestTemplate restTemplate; public void sendGetRequest() { String url = "https://jsonplaceholder.typicode.com/posts/1"; ResponseEntity<String> response = restTemplate.getForEntity(url, String.class); System.out.println(response.getBody()); } ``` 在这个示例中,我们使用 restTemplate.getForEntity() 方法发送一个 GET 请求,并将响应映射为一个 String 类型的实体。然后,我们打印出响应体。 4. 发送 POST 请求 使用 RestTemplate 发送 POST 请求的示例代码如下: ``` @Autowired private RestTemplate restTemplate; public void sendPostRequest() { String url = "https://jsonplaceholder.typicode.com/posts"; HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); String requestBody = "{\"title\": \"foo\", \"body\": \"bar\", \"userId\": 1}"; HttpEntity<String> requestEntity = new HttpEntity<>(requestBody, headers); ResponseEntity<String> response = restTemplate.postForEntity(url, requestEntity, String.class); System.out.println(response.getBody()); } ``` 在这个示例中,我们使用 restTemplate.postForEntity() 方法发送一个 POST 请求,并将请求体设置为一个 JSON 字符串。然后,我们打印出响应体。 总结: 以上就是 Spring Boot RestTemplate配置使用步骤。使用 RestTemplate 可以方便地向 RESTful API 发送请求和接收响应。在使用 RestTemplate 时,可以根据需要配置一些属性,如超时时间等。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值