Create a REST API using Spring MVC
Four, REST client - Reading RestTemplate
RestTemplate Overview
RestTemplate like spring framework can be used to call the rest service in the application that simplifies communication with http services, unified standard RESTful that encapsulates http link, we only need to pass url and return type can be. Commonly used HttpClient, RestTemplate is a more elegant calling RESTful services compared to the previous method.
Access to third-party REST service in the Spring application associated with the use of Spring RestTemplate class.
Design principles RestTemplate like many other Spring * template class (for example JdbcTemplate, JmsTemplate) the same, provides a simplified method with the default behavior is to perform complex tasks.
RestTemplate dependent default capacity provided by the JDK (HttpURLConnection) http connection, if desired, may be replaced, for example, other HTTP library like Apache HttpComponents, Netty or OkHttp by setRequestFactory method.
According to the source structure
RestTemplate class defines some 40 REST methods to interact with resources, most of which correspond to HTTP methods. But careful analysis, which only twelve ways. This overloads the rest are 12 kinds of methods. The following table describes the RestTemplate 12 independent method.
No. | method | The number of overloaded methods | description |
---|---|---|---|
1 | delete() | 3 | Perform HTTP DELETE operation on a specific resource URL |
2 | exchange() | 8 | Perform specific HTTP on the URL method, comprising ResponseEntity returns objects, the object is mapped in the response body obtained |
3 | excute() | 3 | A method performed on a specific HTTP URL, object mapping returns obtained from the response body |
4 | getForObject() | 3 | Sending an HTTP GET request, a request to return the body as an object to map |
5 | getForEntity() | 3 | Sending an HTTP GET request, it returns a response body ResponseEntity contains objects mapped into |
6 | HeadForHeaders() | 3 | Transmitting a HTTP HEAD request, it returns an HTTP header containing a specific resource URL |
7 | optionsForAllow() | 3 | Transmitting a HTTP OPTIONS request, it returns an Allow header information of a particular URL |
8 | postForObject() | 3 | POST data to a URL, the response returns the object matching body is formed |
9 | postForEntity () | 3 | POST data to a URL, returns an object comprising ResponseEntiry, this object is mapped from the body of the response obtained |
10 | postForLocation () | 3 | POST data to a URL, returns the URL of the newly created resource |
11 | put() | 3 | PUT resource to a URL |
12 | patchForObject() | 3 | PATCH data to a URL, the response returns the object matching body is formed |
A simple analysis of the source code can be seen in the following characteristics
In addition to TRACE accident, RestTemplate covers all HTTP verbs. In addition, exchange () and excute () provides a general method to use a lower level of any HTP methods, specific methods are in fact taking the last
excete()
method;Most operations are carried out in a heavy-duty three ways:
- Use java.net.URI as the URL of the form, it does not support parameterized URI;
- Use String as the URL format, and use the Map URL specified parameters;
- Use Strig as the URL format, with variable rub book list identifies the URL parameter.
- RestTemplate contains the following sections:
- HttpMessageConverter Object Converter
- ClientHttpRequestFactory default JDK is the HttpURLConnection
- ResponseErrorHandler Exception Handling
- ClientHttpRequestInterceptor request interceptor
- api located
org.springframework.web.client
under the package - xxForObject () and xxForEntity () method differs Contact
- Different types of return, xxForObject direct return match, but xxForEntity () method returns a ResponseEntity
Object. The body of the deposit with the object into the object mapping, in addition to response to this additional information, such as status codes, HttpHeader information. - Parameter type is consistent
- Different types of return, xxForObject direct return match, but xxForEntity () method returns a ResponseEntity
RestTemplate latest official API
Examples of Use
Get
Source Interface:
<T> T getForObject(String url, Class<T> responseType, Object... uriVariables) throws RestClientException;
<T> T getForObject(String url, Class<T> responseType, Map<String, ?> uriVariables) throws RestClientException;
<T> T getForObject(URI url, Class<T> responseType) throws RestClientException;
<T> ResponseEntity<T> getForEntity(String url, Class<T> responseType, Object... uriVariables)
throws RestClientException;
<T> ResponseEntity<T> getForEntity(String url, Class<T> responseType, Map<String, ?> uriVariables)
throws RestClientException;
<T> ResponseEntity<T> getForEntity(URI url, Class<T> responseType) throws RestClientException;
Simple query, uri years with no arguments
public static void testGet1() { final String uri = "http://localhost:8080/students"; RestTemplate restTemplate = new RestTemplate(); String object = restTemplate.getForObject(uri, String.class); System.out.println(object); }
url parameters
public static void testGet2() { String uri = "http://localost:8080/student/{studentId}"; RestTemplate restTemplate = new RestTemplate(); int studentId = 1; Student student = restTemplate.getForObject(uri, Student.class, studentId); System.out.println(student); }
public static void testGet3() { String uri = "http://localost:8080/student/{studentId}"; RestTemplate restTemplate = new RestTemplate(); int studentId = 1; Map<String, Integer> params = new HashMap<String, Integer>(); params.put("studentId", studentId); Student student = restTemplate.getForObject(uri, Student.class, params); System.out.println(student); }
If GET method request authentication parameters need to be added, and other header information Header, you need to use exchange () method, see below.
Post
Put
Patch
Head
Options
Delete
exchange()
Mentioned above, the difference method xxForEntity () method xxForObject () which returns a response header and the object simultaneously, the status code. It can be read in response to the header information that is useful. But if you want to set the header information in the request sent to the server, then how to do it? This is RestTemplate of exchange () comes in.
exchange () 8 Interface Source:
<T> ResponseEntity<T> exchange(String url, HttpMethod method, @Nullable HttpEntity<?> requestEntity,
Class<T> responseType, Object... uriVariables) throws RestClientException;
<T> ResponseEntity<T> exchange(String url, HttpMethod method, @Nullable HttpEntity<?> requestEntity,
Class<T> responseType, Map<String, ?> uriVariables) throws RestClientException;
<T> ResponseEntity<T> exchange(URI url, HttpMethod method, @Nullable HttpEntity<?> requestEntity,
Class<T> responseType) throws RestClientException;
<T> ResponseEntity<T> exchange(String url,HttpMethod method, @Nullable HttpEntity<?> requestEntity,
ParameterizedTypeReference<T> responseType, Object... uriVariables) throws RestClientException;
<T> ResponseEntity<T> exchange(String url, HttpMethod method, @Nullable HttpEntity<?> requestEntity,
ParameterizedTypeReference<T> responseType, Map<String, ?> uriVariables) throws RestClientException;
<T> ResponseEntity<T> exchange(URI url, HttpMethod method, @Nullable HttpEntity<?> requestEntity,
ParameterizedTypeReference<T> responseType) throws RestClientException;
<T> ResponseEntity<T> exchange(RequestEntity<?> requestEntity, Class<T> responseType)
throws RestClientException;
<T> ResponseEntity<T> exchange(RequestEntity<?> requestEntity, ParameterizedTypeReference<T> responseType)
throws RestClientException;
exchange () method HttpMethod HTTP parameter to indicate the operation to be used. According to this parameter, the above method may work with the same specific HTTP methods.
public void testGet4() {
HttpHeaders headers = new HttpHeaders();
headers.set("kbn-xsrf", "true");
headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
// 手动添加认证
String userName = "root";
String password = "123456";
String str = userName + ":" + password;
String auth = "Basic " + Base64GeneratorUtil.str2Base64(str);
headers.set("Authorization", auth);
// 如果需要 还可以在这里添加一些json字符串信息
String jsonObj = "{}";
HttpEntity<String> request = new HttpEntity<>(jsonObj, headers);
String uri = "http://localost:8080/student/{studentId}";
RestTemplate restTemplate = new RestTemplate();
int studentId = 1;
ResponseEntity<Student> entity = restTemplate.exchange(uri, HttpMethod.PUT, request, Student.class, studentId);
Student student = entity.getBody();
HttpStatus statusCode = entity.getStatusCode();
HttpHeaders headers1 = entity.getHeaders();
}
excute()
slightly.