SpringBoot中RestTemplate的使用
new对象的方式获取RestTemplate
Create a new instance of the RestTemplate using default settings.
** RestTemplate rt = new RestTemplate(); **
配置类
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;@Configuration
public class RestTemplateConfig {@Beanpublic RestTemplate restTemplate(){return new RestTemplate();}
}
RestTemplate的用法
import com.baize.cloud.entities.PayDTO;
import com.baize.cloud.resp.ResultData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;@RestController
public class OrderController {public static final String PaymentSrv_URL = "http://localhost:8001";//先写死,硬编码@Autowiredprivate RestTemplate restTemplate;/*** 一般情况下,通过浏览器的地址栏输入url,发送的只能是get请求* 我们底层调用的是post方法,模拟消费者发送get请求,客户端消费者* 参数可以不添加@RequestBody** @param payDTO* @return*/@GetMapping("/consumer/pay/add")public ResultData addOrder(PayDTO payDTO) {return restTemplate.postForObject(PaymentSrv_URL + "/pay/add", payDTO, ResultData.class);}@GetMapping("/consumer/pay/get/{id}")public ResultData getPayInfo(@PathVariable("id") Integer id) {return restTemplate.getForObject(PaymentSrv_URL + "/pay/get/" + id, ResultData.class, id);}}