首页 > 编程语言 > 详细

我爱Java系列之---【SpringBoot发送Http请求】

时间:2019-08-03 20:16:47      阅读:616      评论:0      收藏:0      [点我收藏+]
Spring的RestTemplate
  • RestTemplate是Rest的HTTP客户端模板工具类
  • 对基于Http的客户端进行封装
  • 实现对象与JSON的序列化与反序列化
  • 不限定客户端类型,目前常用的3种客户端都支持:HttpClient、OKHttp、JDK原生URLConnection(默认方式)
RestTemplate案例
目标:发送Http请求
实现步骤:
1. 创建一个springboot的工程
2. 配置RestTemplate的对象Bean到Spring容器中
3. 在测试类中用@Autowired注入Spring容器中的RestTemplate对象
4. 通过RestTemplate对象的getForObject发送请求
5. 运行测试类的测试方法
技术分享图片

 

技术分享图片

2. 在项目启动类位置中注册一个RestTemplate对象
@Configuration 
public class MyConfiguration { 
    @Bean 
    public RestTemplate restTemplate(){ 
    return new RestTemplate();
     } 
}
3. 在测试类ApplicationTests中 @Autowired 注入RestTemplate
4. 通过RestTemplate的getForObject()方法,传递url地址及实体类的字节码
@RunWith(SpringRunner.class) 
@SpringBootTest 
public class ApplicationTests { 
    @Autowired 
    private RestTemplate restTemplate; 
    @Test 
    public void testREST() { 
    String url = "http://baidu.com"; 
    String json = restTemplate.getForObject(url, String.class);                 
    System.out.println(json);
     } 
}    
  • RestTemplate会自动发起请求,接收响应
  • 并且帮我们对响应结果进行反序列化
5. 运行测试类中的testREST方法;

技术分享图片

 

我爱Java系列之---【SpringBoot发送Http请求】

原文:https://www.cnblogs.com/hujunwei/p/11295787.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!