TZ_12_Spring的RestTemplate

1. Http Client Tools

  HttpClient: HttpClient Apache is the company's products, is a component in the Http Components.

 Features:

  • Standards-based, pure Java language. Realized Http1.0 and Http1.1

  • In object-oriented extensible structure achieved full Http method (GET, POST, PUT, DELETE, HEAD, OPTIONS, and TRACE)

  • Support for HTTPS protocol.

  • Http establish a transparent connection through a proxy.

  • Automatic Processing Set-Cookie Cookie.

 

2 This interface returns a User object, but we have to be the actual Json string User needs me, and we manually into the User object at this time can make use of the 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 provides a template RestTemplate tools, Http client based on the package, and achieves serialization and deserialization of the objects json, very convenient. RestTemplate not limited Http client type, but the abstract, are currently used three kinds of support:

  1>HttpClient

  2>OkHttp

  3> JDK the URLConnection native (default)

 

4. Start the class is registered in position:

  

@Bean
     public Residual Template rest template () { 
        
        return  new Rest Template (); 
    }

 

 Directly in the test class @Autowiredinjection: 

@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);
    }

}

 

Guess you like

Origin www.cnblogs.com/asndxj/p/11455071.html