In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-09 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article will explain in detail what are the restTemplate points for you to pay attention to using spring. The editor thinks it is very practical, so I share it with you as a reference. I hope you can get something after reading this article.
Pay attention to restTemplate using spring
The restTemplate of spring can send a request to an url and receive server-side response information. However, when a request is made, the URL value of the request is encoded and then sent.
Let's take a look at the source code of spring's RestTemplate
Basically, the execute () method is called inside the method that restTemplate sends the request:
The code for the expand () method is as follows:
The code for the encode () method is as follows:
So if you use a non-spring server to receive it, you need to decode it to receive the content sent by RestTemplate. (spring's server will automatically decode once when it receives parameters, so use restTemplate to send messages, and Spring's server will not have a problem with receiving them.)
Spring's guide to using RestTemplate
Nowadays, the interface of restful is more and more extensive, but now many interfaces abandon the traditional webService development mode with complex configuration. In the field of java, only a very simple springMvc can be declared as a controller. Coupled with the service layer, you can directly operate the database to become a flexible interface.
And we will request the interface more and more times (recently, when I was docking with a tool, we called all the interfaces provided by the other company on our own initiative). Generally, when we request the interface, we all use the Apache Httpclient tool, which is stable, can establish long-term connections and maintain good performance, but its only disadvantage is that it is troublesome to use and requires many layers to judge and deal with it. What I'm going to talk about today is spring's re-encapsulation of httpClient's utility class, restTemplate, an efficient tool abstracted from template patterns.
It's a bit like jdbcTemplate. Today we'll uncover how to use it step by step.
One: introduction to restTemplate
Class structure of 1.1:restTemplate
You can see that it inherits from HttpAccessor, a unified processor, and then inherits from InterceptingHttpAccessor, an intercept converter, and finally RestTemplate implements a template tool class that encapsulates httpClient.
1.2:restTemplate 's method
Spring is the central class used to synchronize client HTTP access. It simplifies communication with HTTP servers and implements RESTful principles. It handles HTTP connections, causes the application code to provide URL, uses possible template variables, and extracts the results.
Note: by default, RestTemplate relies on standard JDK to establish HTTP connections. You can switch to use different HTTP libraries, such as Apache HttpComponents,Netty and OkHttp through the setRequestFactory attribute. Internal templates use HttpMessageConverter instances to convert HTTP messages to POJO and from POJO. Converters of the main MIME type are registered by default, but you can also register other converters through setMessageConverters
The following is the comparison mapping between the http method and the restTempalte method. You can see that restTemplate provides a method to manipulate http, in which the exchange method can be used to make any request. Generally, we use it to encapsulate different request methods.
Second: the configuration method of restTemplate
2.1: configuration in springboot
Springboot is a development method that simplifies the traditional xml configuration, mainly using annotations to replace the traditional tedious xml configuration. Next, we use the annotations provided by springboot to configure restTemplate:
@ Configurationpublic class RestTemplateConfig {private static final Logger logger= LoggerFactory.getLogger (RestTemplateConfig.class); @ Bean public RestTemplate restTemplate () {/ / add a content converter, using the default content converter RestTemplate restTemplate = new RestTemplate (httpRequestFactory ()); / / set the encoding format to UTF-8 List converterTarget = null For (HttpMessageConverter item: converterList) {if (item.getClass () = = StringHttpMessageConverter.class) {converterTarget = item; break;}} if (converterTarget! = null) {converterList.remove (converterTarget);} HttpMessageConverter converter = new StringHttpMessageConverter (StandardCharsets.UTF_8); converterList.add LOGGER.info ("- restTemplate- initialization complete"); return restTemplate;} @ Bean public ClientHttpRequestFactory httpRequestFactory () {return new HttpComponentsClientHttpRequestFactory (httpClient ());} @ Bean public HttpClient httpClient () {/ / persistent connection for 30 seconds PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager (30, TimeUnit.SECONDS) / / set the maximum number of connections in the entire connection pool to determine connectionManager.setMaxTotal (500) according to your own scenario; / / the concurrency of the same route, which is a subdivision of maxTotal connectionManager.setDefaultMaxPerRoute (500) / / requestConfig RequestConfig requestConfig = RequestConfig.custom () / / time for the server to return data (response), after which read timeout .setSocketTimeout (10000) / / time to connect to the server (handshake successful) Throw connect timeout .setConnectTimeout (5000) / / get the connection timeout from the connection pool beyond this time. If no available connection is obtained after this time, org.apache.http.conn.ConnectionPoolTimeoutException: setConnectionRequestTimeout (5000). Build () / / headers List headers = new ArrayList (); headers.add (new BasicHeader ("User-Agent", "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.16 Safari/537.36"); headers.add (new BasicHeader ("Accept-Encoding", "gzip,deflate"); headers.add (new BasicHeader ("Accept-Language", "zh-CN")) Headers.add (new BasicHeader ("Connection", "Keep-Alive")); headers.add (new BasicHeader ("Content-type", "application/json;charset=UTF-8")) Return HttpClientBuilder.create () .setDefaultRequestConfig (requestConfig) .setConnectionManager (connectionManager) .setDefaultHeaders (headers) / / keep persistent connection configuration. You need to add Keep-Alive .setKeepAliveStrategy (new DefaultConnectionKeepAliveStrategy ()) / / number of retries in the header. Default is 3 times. Did not open .setRetryHandler (new DefaultHttpRequestRetryHandler (2, true)) .build () }}
First explain the following @ configuration, its main function is to initialize IOC when the spring container starts, using this annotation, then this class will do dependency injection of the class identified by the @ Bean annotation when the spring starts. If @ Bean understands it, it's like configuring it in a configuration file. The next step is to add the factory of httpRequest to the constructor of restTemplate, use connection pooling to optimize http communication, default to use long connection time of 30 seconds, set the route to direct http connections to the specified IP, and then set the number of concurrency. The second is to set the timeout time for the request configuration, in order to prevent the excessive waste of resources caused by too long request time. If no data is returned at the timeout that exceeds the setting, the connection is disconnected directly. Headers is to add the default request header, where the format of the transmission is set to json, the language is Chinese-English, and so on. HttpClientBuilder.create sets the request header to HttpClient, and then injects it into httpClient for encapsulation after setting the hold time and the number of retries.
HttpMessageConverter in bean is the http information converter. Its main function is to convert and parse the returned json data. By default, restTemplate uses jackson as the underlying parsing tool, while other third-party open source libraries, such as Gson,fastjson, are placed in the headers list. If you want to use it, you can change it through the following code:
This.restTemplate.getMessageConverters (). Clear (); final List > (); / / self-implemented messgeConverter HttpMessageConverter messageConverter = new MyHttpMessageConverter (); myHttpMessageConverter.add (messageConverter); this.restTemplate.setMessageConverters (myHttpMessageConverter); III: restUtil utility class
RestUtil is a way to expose the outside world by wrapping restTemplate. Through high encapsulation, you can hide the internal details and make it easy to use. When using it, we only need to pass in the request url and corresponding parameters, and then you can get the result. Generally speaking, there are two forms of parameters, one is directly passed into json, the other is in the form of key, value or key/value. You can use the execute method directly, and just pass in url and the method type of the request. At the beginning, we saw that restTemplate basically supports all http requests. The next utility class will introduce the main encapsulation methods of post and get requests.
@ Componentpublic class RestUtil {@ Autowired private RestTemplate restTemplate; / / some custom request header parameters public static final String supplierID= "; public static final String interfacekey=" / * * DLT dedicated execution method * @ param param request parameters: you can add some constant request values * @ url * @ param method request method * @ return * / public String execute (Map param, String url, HttpMethod method) {HttpHeaders headers = this.getDefaultHeader (); Map requestor = this.getDefaultParam (); param.put ("requestor", requestor) Param.put ("supplierID", supplierID); HttpEntity requestEntity = new HttpEntity (param, headers); ResponseEntity response = restTemplate.exchange (url,method, requestEntity, String.class); return response.getBody ();} / * get the default header request information * @ return * / public HttpHeaders getDefaultHeader () {String timestamp = "" + System.currentTimeMillis () String signature = EncoderByMd5 (supplierID + timestamp + interfacekey); HttpHeaders headers = new HttpHeaders (); headers.add ("signature", signature); headers.add ("timestamp", timestamp); return headers;} / * * get the default parameter * @ return * / public Map getDefaultParam () {Map defParam = new HashMap () DefParam.put ("invoker", "xx"); defParam.put ("operatorName", "xx"); return defParam;} / * * encrypted via MD5 * @ param str * @ return * / public static String EncoderByMd5 (String str) {if (str = = null) {return null } try {/ / determine the calculation method MessageDigest md5 = MessageDigest.getInstance ("MD5"); BASE64Encoder base64en = new BASE64Encoder (); / / encrypted string return base64en.encode (md5.digest (str.getBytes ("utf-8")). ToUpperCase ();} catch (NoSuchAlgorithmException | UnsupportedEncodingException e) {return null }} / * get request * @ param url request url * @ param jsonData request json * @ return * / public String restGet (String url,String jsonData) {return request (url, jsonData,HttpMethod.GET) } / * @ param url requested url * @ param jsonData json data * @ param httpMethod * @ return * / private String request (String url, String jsonData,HttpMethod httpMethod) {ResponseEntity response=null; try {if (Check.isEmpty (url)) {throw new IllegalArgumentException ();} HttpEntity requestEntity = new HttpEntity (jsonData) Response = restTemplate.exchange (url, httpMethod, requestEntity, String.class);} catch (Exception ex) {ex.printStackTrace (); return ";} return response.getBody () .toString () } / * Get request to get entity class * @ param url request url * @ param responseType returned type * @ param parms unlimited number of parameters * @ param generic * @ return * / public T getForEntity (String url,Class responseType,Object... Parms) {return (T) restTemplate.getForEntity (url,responseType,parms);} / * Get request * @ param url * @ param parm * @ return * / public String get (String url,Map parm) {return restTemplate.getForEntity (url,String.class,parm). GetBody ();}} IV: use example
4.1First, let's use springBoot to build a simple rest request link
Let's simulate a request, pass in the interface of age, sex and height, and calculate the standard weight. This code is relatively simple. I only give the demonstration code:
@ SpringBootApplication@RestControllerpublic class HealApplication {@ RequestMapping (value = "weight", method = RequestMethod.GET) public ResultModel getWeight (@ RequestParam (value = "height", required = false) Integer height, @ RequestParam (value = "sex", required = false) Integer sex, @ RequestParam (value = "age" Required = false) Integer age) {if (height = = null | | age = = null | | sex = = null | | (! sex.equals (0) & &! sex.equals (1)) {return new ResultModel (400, "missing or incorrect request parameters", 0d) } double condition = getStandardWeight (sex, age, height); return new ResultModel (200, "request successful", condition) 1: male 2: female * @ param age age * @ param height * @ return weight (in kg) * / public double getStandardWeight (int sex, int age, int height) {double weight = 0.0 Switch (sex) {/ / male case 1: if (age
< 12 && age >2) {weight = age * 2 + 12;} else if (age > 12) {weight = (height-150) * 0.6 + 50;} break; case 0: if (age)
< 12 && age >2) {weight = age * 2 + 12;} else if (age > 12) {weight = (height-100) * 0.6 + 50;} break; default: weight = 0; break;} return weight;}
You can see that our controller has a method for mapping weight requests. The standard weight can be calculated by passing in age, height and sex. Let's launch springBoot and try to access it with a browser. We can see the following results:
4.2: in order to show that the interface is open, let's try it with postman, and we can see that the returned result is correct:
Introduce the testNg unit test class into springboot to test the results of accessing this link:
The public class TestRestManager extends OrderProviderApplicationTests {@ Autowired private RestUtil restUtil; / * request method is GEt * @ return * / @ Test private void requestGet () {String url= "http://localhost:8080/weight?age={age}&sex={sex}&height={height}"; / / assembly request parameter Map parmMap = new HashMap (); parmMap.put (" age ", 35) ParmMap.put ("sex", 1); parmMap.put ("height", 178); String result = restUtil.get (url, parmMap); System.out.println (result);}}
The result returns the following:
This is the end of this article on "what are the restTemplate points for using spring". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, please share it for more people to see.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.