Original: Curly brace MC(wechat official account: Huakuohao-MC), welcome to share, please keep the source.

In these days of microservices, HTTP calls are routine operations that programmers can’t avoid.

RestTemplate is a client provided by Spring for making HTTP calls. RestTemplate is simpler and more convenient to use than traditional HttpComponents.

Making a Get request
  1. To obtainJSONType return
RestTemplate restTemplate = new RestTemplate();
String fooResourceUrl = "http://localhost:8080/spring-rest/foos";
ResponseEntity<String> response = restTemplate.getForEntity(fooResourceUrl + "/ 1", String.class);
assertThat(response.getStatusCode(), equalTo(HttpStatus.OK));
Copy the code
  1. To obtainPOJOType return

Let’s define a Foo class

public class Foo implements Serializable {
    private long id;
    private String name; 
    // standard getters and setters 
 }
Copy the code

Use the RestTemplate to initiate a Get request

Foo foo = restTemplate .getForObject(fooResourceUrl + "/ 1", Foo.class); 
assertThat(foo.getName(), notNullValue()); assertThat(foo.getId(), is(1L));
Copy the code
Get Header information
HttpHeaders httpHeaders = restTemplate.headForHeaders(fooResourceUrl); 
/ / get ContentType
assertTrue(httpHeaders.getContentType().includes(MediaType.APPLICATION_JSON));
Copy the code
Making a Post request
RestTemplate restTemplate = new RestTemplate(); HttpEntity<Foo> request = new HttpEntity<>(new Foo("bar"));
Foo foo = restTemplate.postForObject(fooResourceUrl, request, Foo.class);
assertThat(foo, notNullValue());
assertThat(foo.getName(), is("bar"));
Copy the code
Simulate Form submission

To submit form data through POST, first set header information and set content-Type to Application/X-www-form-urlencoded.

Next we wrap the data items in the form into a Map. Finally, wrap the Header and form data together as an HttpEntity.

An example of this code is as follows

HttpHeaders headers = new HttpHeaders(); 
// Set the header information
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
// Encapsulate the form information into a Map
MultiValueMap<String, String> map= new LinkedMultiValueMap<>(); 
map.add("id"."1");

// Encapsulate form data into HttpEntity
HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(map, headers);

// Initiate a POST request
ResponseEntity<String> response = restTemplate.postForEntity( fooResourceUrl+"/form", request , String.class);

assertThat(response.getStatusCode(), is(HttpStatus.CREATED));
Copy the code
Update resources in PUT mode

Resources can be updated either through the PUT method or through Exchange (). The following is an example.

Foo updatedInstance = new Foo("newName"); 

updatedInstance.setId(createResponse.getBody().getId()); 

String resourceUrl = fooResourceUrl + '/' + createResponse.getBody().getId();
HttpEntity<Foo> requestUpdate = new HttpEntity<>(updatedInstance, headers); 
// Send a PUT request through exchange
template.exchange(resourceUrl, HttpMethod.PUT, requestUpdate, Void.class);

// Update directly through putAPI
template.put(resourceUrl,requestUpdate,Void.class);
Copy the code
Making a DELETE request

Delete a resource by delete.

String entityUrl = fooResourceUrl + "/" + existingResource.getId();
restTemplate.delete(entityUrl);
Copy the code
Initiate a request through Exchange ()

Any type of HTTP request can be made through the Exchange () method. An example of this code is shown below.

RestTemplate restTemplate = new RestTemplate();
HttpEntity<Foo> request = new HttpEntity<>(new Foo("bar")); 
// The pass parameter is httpmethod. POST, and the POST type parameter is initiated
ResponseEntity<Foo> response = restTemplate .exchange(fooResourceUrl, HttpMethod.POST, request, Foo.class);
assertThat(response.getStatusCode(), is(HttpStatus.CREATED));
Foo foo = response.getBody();
assertThat(foo, notNullValue());
assertThat(foo.getName(), is("bar"));
Copy the code
Configuring the Timeout Period

You can use ClientHttpRequestFactory to set the timeout period for the RestTemplate. A code example is as follows:

RestTemplate restTemplate = new RestTemplate(getClientHttpRequestFactory()); 

private ClientHttpRequestFactory getClientHttpRequestFactory(a) {
    int timeout = 5000;
    HttpComponentsClientHttpRequestFactory clientHttpRequestFactory = new HttpComponentsClientHttpRequestFactory(); 

    clientHttpRequestFactory.setConnectTimeout(timeout);
    return clientHttpRequestFactory;
}
Copy the code
conclusion

RestTemplate is simple and convenient to use, and is designed in much the same way as JDBCTemplate. I believe this is also the philosophy of Spring.

Note: RestTemplate is no longer officially recommended and WebClient is officially recommended. The next article will cover the use of WebClient.

This article is mainly translated from www.baeldung.com/rest-templa…

Recommended reading

1. Java concurrent programming stuff (10) — Final summary

2. Common network problem locating tools that programmers should master

3. Do you know how to use Awk

4. Teach you how to build a set of ELK log search operation and maintenance platform

Original: Curly brace MC(wechat official account: Huakuohao-MC) Focus on JAVA basic programming and big data, focus on experience sharing and personal growth.