Basic concepts
Spring RestTemplate is a client provided by Spring for accessing Rest services. RestTemplate provides a variety of convenient access to remote Http services, which can greatly improve the writing efficiency of the client. Therefore, many clients such as Android or third-party service providers use RestTemplate to request restful services.
Spring-web's RestTemplata is an encapsulation of Java's underlying http. Users using RestTemplata can no longer pay attention to the underlying connection establishment. RestTemplata not only supports the Rest specification, but also defines the return value object type.
In use, you can directly new a RestTemplate object. There will be some message converters that return messages in the RestTemplate object we created. 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 yourself, create a class that inherits the AbstractGenericHttpMessageConverter<T> class or implements the HttpMessageConverter<T> interface. It should be noted that the canRead method and the canWrite method should be judged by yourself, write parameters to the stream in the writeInternal or write method, and get the returned result from the stream's body in the readInternal or read method and type map.
The RestTemplate object creates HTTP requests at the bottom by using the implementation under the java.net package. You can specify different HTTP request methods by using ClientHttpRequestFactory.
The ClientHttpRequestFactory interface mainly provides two implementation methods:
RestTemplate uses SimpleClientHttpRequestFactory by default, and internally calls HttpConnection to call jdk. The default timeout is -1. We can define the timeout ourselves.
SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();//Set the connection timeout, unit millisecond factory.setConnectTimeout(5000);//Set the read timeout, unit millisecond factory.setReadTimeout(10000); RestTemplate restTemplate = new RestTemplate(factory);
Use GET requests:
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 get request to splice the parameters directly to the address. I don’t know why. If you use the third parameter, even the MultiValueMap type will not work (some people on the Internet say that using the MultiValueMap type is OK, but I tried it but it won’t work)
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 HTTP header entity and fill in header information, such as data format HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8);//Create HTTP entity, you can directly use the constructor to put the request body and the request header in HttpEntity<String> httpEntity = new HttpEntity<String>(jsonStr2, httpHeaders);String url = "http://localhost:80/mandy/user_enable.json";//Calling 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 requests:
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 HTTP header entity and fill in header information, such as data format HttpHeaders httpHeaders = new HttpHeaders();httpHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8);//Create HTTP entity, 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); }A small disadvantage of this method is that there is no return value of the request result. If you need to use the return value, you cannot use this method.
If you want to use a delete type request, there are only the following types in the parameter column of the put method of RestTemplate
@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 parameters and let us put the request body content, so if you want to use the Delete method provided by RestTemplate directly, the interface must use restful style, put the parameters in the address, and obtain the parameters through the @PathVariable(value="") annotation.
Key point: In fact, we can directly use the exchange method of RestTemplate, as follows
@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);}Here we only list one method. The others can be found in the source code. This method can make all types of requests.
In this method, the method parameter can be obtained through the HTTPMethod enumeration. The requestEntity parameter is the HttpEntity entity encapsulated by itself, including the request body and the request header. The responseType parameter is a mapping class that returns the result. The uriVariables parameter gives me the impression that it is useless (personal opinion). The access to the request return interface can be obtained through the getBody() method of the method return value.
The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.