TZ_12_Spring的RestTemplate

1.Http客户端工具

  HttpClient:HttpClient是Apache公司的产品,是Http Components下的一个组件。

 特点:

  • 基于标准、纯净的Java语言。实现了Http1.0和Http1.1

  • 以可扩展的面向对象的结构实现了Http全部的方法(GET, POST, PUT, DELETE, HEAD, OPTIONS, and TRACE)

  • 支持HTTPS协议。

  • 通过Http代理建立透明的连接。

  • 自动处理Set-Cookie中的Cookie。

 

2这个接口返回一个User对象,但我们实际的到是一个User的Json字符串需要我,们手动的转为User对象 此时就可以借助Spring的RestTemplate

@Test
public void testGetPojo() throws IOException {
    HttpGet request = new HttpGet("http://localhost/hello");
    String response = this.httpClient.execute(request, new BasicResponseHandler());
    System.out.println(response);
}

 

3.Spring的RestTemplate

Spring提供了一个RestTemplate模板工具类,对基于Http的客户端进行了封装,并且实现了对象与json的序列化和反序列化,非常方便。RestTemplate并没有限定Http的客户端类型,而是进行了抽象,目前常用的3种都有支持:

  1>HttpClient

  2>OkHttp

  3>JDK原生的URLConnection(默认的)

4.在启动类位置注册:

  

 @Bean
    public RestTemplate restTemplate() {
        
        return new RestTemplate();
    }

 

 在测试类中直接@Autowired注入: 

@RunWith(SpringRunner.class)
@SpringBootTest(classes = HttpDemoApplication.class)
public class HttpDemoApplicationTests {

    @Autowired
    private RestTemplate restTemplate;

    @Test
    public void httpGet() {
        User user = this.restTemplate.getForObject("http://localhost:8080/User/1.html", User.class);
        System.out.println(user);
    }

}

猜你喜欢

转载自www.cnblogs.com/asndxj/p/11455071.html