As a Java developer, usually call external services are through PRC interface, but this business downstream only provides Http interface, it is a little anxious…

Basic use of RestTemplate

RestTemplate is a Restful HTTP request template implemented by Spring. Using RestTemplate simplifies the complexity of request operations while standardizing the code style.

A Get request

// Convert the returned result into a POJO object
public <T> T getForObject(String url, Class<T> responseType)

// Return Http native information (status code, request header, body)
public <T> ResponseEntity<T> getForEntity(String url, Class<T> responseType)
Copy the code

Practice: Get nuggets today’s motto

@Data
public class Result<T> implements Serializable {
    private int err_no;
    private String err_msg;
    private T data;
}

private String urlFormat = "https://api.juejin.cn/growth_api/v1/get_coder_calendar?aid=%s&uuid=7037140143551399436";

private RestTemplate restTemplate = new RestTemplate();

@Test
public void testGet(a) {
    String url = String.format(urlFormat, "xxx");
    Result result = restTemplate.getForObject(url, Result.class);
    System.out.println(result);
}
Copy the code

Nuggets sign today quote:

Result(err_no=0, err_msg=success, data={aphorism= document writing ability is just as important to engineers as code ability, should_or_not=Copy the code

A Post request

// Convert the returned result into a POJO object
public <T> T postForObject(String url, Object request, Class<T> responseType)

// Return Http native information (status code, request header, body)
public <T> ResponseEntity<T> postForEntity(String url, Object request, Class<T> responseType)
Copy the code

Practice: Nuggets automatic lottery

private String urlFormat = "https://api.juejin.cn/growth_api/v1/lottery/draw?aid=%s&uuid=6994739894300935684&_signature=_02B4Z6wo00901IFbWBAAAIDCsQ 1vhfdqjSiBXlyAAEICZNX6.YFOgtHG7h9uKHxa1gwR5xaQh55ytA4gMUM6N9JboQDq5siTnpplhowAUX5HCv6Raat44rC31FskryqQD2bKbOyfkMoyJXev06 ";
private String cookie = "xxx";

private RestTemplate restTemplate = new RestTemplate();

public void testPost(a) {
    String url = String.format(urlFormat, "2608");
    / / request header
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);
    headers.set(HttpHeaders.COOKIE, cookie);
    / / request body
    JSONObject body = new JSONObject();
    HttpEntity<String> request = new HttpEntity(body.toString(), headers);
    Result result = restTemplate.postForObject(urlFormat, request, Result.class);
    System.out.println(((Map) result.getData()).get("lottery_name"));
}
Copy the code

Extended knowledge of RestTemplate

  1. The getForObject() method cannot pass a value to a request header Hearder. You can use the underlying common methods Exchange () or excute().
  2. #Springboot — a more elegant way to send HTTP requests.
  3. #RestTemplate adds timeout handling to ClientHttpRequestFactory options #RestTemplate source parsing (directory) # HttpClient some thoughts on connection pooling

RestTemplate Development template

@Configuration
public class RestTemplateConfig {

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

    @Bean
    public HttpClientConnectionManager poolingConnectionManager(a) {
        PoolingHttpClientConnectionManager poolingConnectionManager = new PoolingHttpClientConnectionManager();
        // The maximum number of connections in the entire thread pool
        poolingConnectionManager.setMaxTotal(200);
        // Maximum number of concurrent routes to a host
        poolingConnectionManager.setDefaultMaxPerRoute(100);
        return poolingConnectionManager;
    }

    @Bean
    public ClientHttpRequestFactory clientHttpRequestFactory(a) {
        HttpComponentsClientHttpRequestFactory clientHttpRequestFactory = new HttpComponentsClientHttpRequestFactory();
        HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
        httpClientBuilder.setConnectionManager(poolingConnectionManager());
        clientHttpRequestFactory.setHttpClient(httpClientBuilder.build());
        // The timeout period for establishing a connection between the client and the server
        clientHttpRequestFactory.setConnectTimeout(1000);
        // Timeout for the client to read data from the server
        clientHttpRequestFactory.setReadTimeout(3000);
        returnclientHttpRequestFactory; }}Copy the code