org.springframework.web.client.RestTemplate 的使用

目录

  • 前言
  • 使用
    • 配置
    • 具体使用

前言

后端难免会发送请求,大致分为两种请求:微服务之间的内部请求和系统之间的外部请求,org.springframework.web.client.RestTemplate对这两种请求都支持。

使用

配置

import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;

@Configuration
public class RestTemplateConfig {
   /** 
     微信服务间的内部调用配置
   */
    @Bean(value = {"restTemplateFeign"})
    @LoadBalanced
    public RestTemplate restTemplateFeign() {
        return new RestTemplate();
    }

	/** 
     外部调用配置
   */
    @Bean(value = "restTemplateHttp")
    public RestTemplate restTemplateHttp() {
        return new RestTemplate();
    }
}

具体使用

1、内部调用
注入

@Autowired
private RestTemplate restTemplateFeign;

调用

/**
     * @Descriptio 发送请求
     * @param billPushObject
     * @return com.hw.common.web.AjaxResult
     */
    private AjaxResult send(String pushUrl,JSONObject billPushObject){
        AjaxResult ajaxResult = restTemplateFeign.postForObject(pushUrl,billPushObject, AjaxResult.class);
        Integer code = (Integer) ajaxResult.get(AjaxResult.CODE_TAG);
        if(code == 200){

        }
        return ajaxResult;
    }

2、外部调用
注入

@Resource(name = "restTemplateHttp")
private RestTemplate restTemplateHttp;

调用

public LoginUser regionLoginSso(String ticket) {
        log.info("致信oa调用登录ticket:{}", ticket);
        String url = seeyonUrl + ticket;
        log.info("致信oa调用登录url:{}", url);
        String reson = restTemplateHttp.getForObject(url, String.class);
        log.info("致信oa调用成功参数:{}", reson);
        if(org.springframework.util.StringUtils.isEmpty(reson)){
            throw new CustomException("用户不存在!");
        }
        String[] split = reson.split("\n");
        return regionLoginSsoByTicket(split[0]);
    }

你可能感兴趣的:(JAVA,SpringCloud,java)