The specific method used by Spring RestTemplata, springresttemplata

Source: Internet
Author: User

The specific method used by Spring RestTemplata, springresttemplata

Basic Concepts

Spring RestTemplate is a client provided by Spring for accessing the Rest service. RestTemplate provides a variety of convenient methods to access the remote Http service, which can greatly improve the writing efficiency of the client, therefore, many clients such as Android and third-party service providers use RestTemplate to request restful services.

RestTemplata of spring-web is an encapsulation of the underlying http of java. With RestTemplata, users can no longer pay attention to the establishment of underlying connections. In addition, RestTemplata not only supports Rest specifications, but also defines the type of returned object.

In use, you can directly create a new RestTemplate object. In the RestTemplate object we created, there will be some message converters that return messages. You can find the corresponding Converter Based on the MediaType of the returned data and perform MediaType conversion. You can also create a message Converter by yourself, create a class that inherits the AbstractGenericHttpMessageConverter <T> class, or implement the HttpMessageConverter <T> interface. It is important to note that the canRead and canWrite methods are best performed by yourself, write parameters to the stream in the writeInternal or write method. In the readInternal or read method, obtain the returned results from the stream body and perform type ing.

The RestTemplate object creates an HTTP request using the implementation of the java.net package at the underlying layer. You can use ClientHttpRequestFactory to specify different HTTP request methods.

The ClientHttpRequestFactory interface provides two implementation methods:

  1. One is SimpleClientHttpRequestFactory, which uses the method provided by J2SE (provided by the java.net package) to create the underlying Http request connection.
  2. One way is to use HttpComponentsClientHttpRequestFactory. The underlying layer uses HttpClient to access remote Http Services, and HttpClient can be used to configure information such as connection pools and certificates.

By default, RestTemplate uses SimpleClientHttpRequestFactory and calls jdk HttpConnection internally. The default timeout value is-1. You can customize the timeout value.

SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory (); // sets the connection timeout, in milliseconds. factory. setConnectTimeout (5000); // set read timeout, in milliseconds factory. setReadTimeout (10000); RestTemplate restTemplate = new RestTemplate (factory );

Use GET request:

String url = "http://localhost:80/mandy/login.json?account=123456&password=123456";Result res = restTemplate.getForObject(url, Result.class);

RestTemplate source code:

  @Override public <T> T getForObject(String url, Class<T> responseType, Object... urlVariables) throws RestClientException {  RequestCallback requestCallback = acceptHeaderRequestCallback(responseType);  HttpMessageConverterExtractor<T> responseExtractor =    new HttpMessageConverterExtractor<T>(responseType, getMessageConverters(), logger);  return execute(url, HttpMethod.GET, requestCallback, responseExtractor, urlVariables); }

It is best to use a get request to directly concatenate the parameter to the address. I don't know why. If the third parameter is used, even the MultiValueMap type will not work. (Some people say that the MultiValueMap type is acceptable, I tried)

Use POST request:

HashMap <String, Object> map = new HashMap <String, Object> (); map. put ("name", "test"); map. put ("account", "qwer"); map. put ("password", "qwer"); ObjectMapper mapper = new ObjectMapper (); String jsonStr = null; try {jsonStr = mapper. writeValueAsString (map);} catch (Exception e) {e. printStackTrace ();} // create an HTTP header entity and fill in the header information, such as the data format HttpHeaders httpHeaders = new HttpHeaders (); httpHeaders. setContentType (MediaType. APPLICATION_JSON_UTF8); // create an HTTP object. You can directly use the constructor to put the request body and request header in HttpEntity <String> httpEntity = new HttpEntity <String> (jsonStr2, httpHeaders ); string url = "http: // localhost: 80/mandy/user_enable.json"; // call the method to request Result res2 = restTemplate. postForObject (url, httpEntity, Result. class );

RestTemplate source code:

  @Override public <T> T postForObject(String url, Object request, Class<T> responseType, Object... uriVariables)   throws RestClientException {  RequestCallback requestCallback = httpEntityCallback(request, responseType);  HttpMessageConverterExtractor<T> responseExtractor =    new HttpMessageConverterExtractor<T>(responseType, getMessageConverters(), logger);  return execute(url, HttpMethod.POST, requestCallback, responseExtractor, uriVariables); }

Use PUT request:

HashMap <String, Object> map = new HashMap <String, Object> (); map. put ("user_id", "1"); map. put ("enable", 0); ObjectMapper mapper = new ObjectMapper (); String jsonStr = null; try {jsonStr = mapper. writeValueAsString (map);} catch (JsonProcessingException e) {e. printStackTrace ();} // create an HTTP header entity and fill in the header information, such as the data format HttpHeaders httpHeaders = new HttpHeaders (); httpHeaders. setContentType (MediaType. APPLICATION_JSON_UTF8); // create an HTTP object. You can directly use the constructor to put the request body and request header in HttpEntity <String> httpEntity = new HttpEntity <String> (jsonStr, httpHeaders ); string url = "http: // localhost: 80/mandy/user_enable.json"; restTemplate. put (url, httpEntity );

RestTemplate source code:

  @Override public void put(String url, Object request, Object... urlVariables) throws RestClientException {  RequestCallback requestCallback = httpEntityCallback(request);  execute(url, HttpMethod.PUT, requestCallback, null, urlVariables); }

The disadvantage of this method is that there is no returned value for the request result. If the return value is required, this method cannot be used.

If you want to use a delete request, the RestTemplate put method has only the following parameter columns:

@Overridepublic void delete(String url, Object... urlVariables) throws RestClientException {  execute(url, HttpMethod.DELETE, null, null, urlVariables);}@Overridepublic void delete(String url, Map<String, ?> urlVariables) throws RestClientException {  execute(url, HttpMethod.DELETE, null, null, urlVariables);}@Overridepublic void delete(URI url) throws RestClientException {  execute(url, HttpMethod.DELETE, null, null);}

These methods do not give us the parameter to let us put the request body content. Therefore, if you want to directly use the Delete method provided by RestTemplate, the interface must use the restful style and put the parameter in the address, obtain the parameter through the @ PathVariable (value = "") annotation.

Important: in fact, we can directly use the RestTemplate exchange method, as shown below:

@Overridepublic <T> ResponseEntity<T> exchange(String url, HttpMethod method,  HttpEntity<?> requestEntity, Class<T> responseType, Object... uriVariables) throws RestClientException {  RequestCallback requestCallback = httpEntityCallback(requestEntity, responseType);  ResponseExtractor<ResponseEntity<T>> responseExtractor = responseEntityExtractor(responseType);  return execute(url, method, requestCallback, responseExtractor, uriVariables);}

Only one method is listed here. Others can see the source code. This method can be used for all types of requests.

In this method, the method parameter can be obtained through the HTTPMethod enumeration. The requestEntity parameter is a self-encapsulated HttpEntity entity, including the Request body and request header. The responseType parameter is the ing Class of the returned results, the uriVariables parameter impressed me (in my opinion). The getBody () method returned by the method can be used to obtain the Request Response interface.

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.