Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How does SpringBoot use RestTemplate to call the interface

2025-01-30 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article introduces the knowledge of "how SpringBoot uses RestTemplate to call the interface". Many people will encounter this dilemma in the operation of actual cases, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

Catalogue

Use RestTemplate to call the interface

1. Create a new configuration class to configure RestTemplate's Beanimport org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.http.client.ClientHttpRequestFactory;import org.springframework.http.client.SimpleClientHttpRequestFactory;import org.springframework.web.client.RestTemplate; / * RestTemplate configuration template * * @ author like * / @ Configurationpublic class RestTemplateConfig {@ Bean public RestTemplate restTemplate (ClientHttpRequestFactory factory) {return new RestTemplate (factory) } @ Bean public ClientHttpRequestFactory simpleClientHttpRequestFactory () {SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory (); factory.setReadTimeout (5000); / / in ms factory.setConnectTimeout (5000); / / in ms return factory;}}

Note: if you prompt in the compiler that factory cannot be injected automatically, it should conflict with other classes and have multiple ClientHttpRequestFactory

Just change the name of this factory to something else, for example, directly change it to simpleClientHttpRequestFactory here.

two。 Multiple ways to transmit and receive parameters

2.1postForObject method

PostForObject refers to the post request and returns an Object object.

New HttpEntity (request body)

New HttpEntity (request header)

New HttpEntity (request body, request header)

2.1.1 use Json to transmit and receive data

First introduce the pom configuration of fastJson

Com.alibaba fastjson 1.2.49

Inject RestTemplate into the implementation class

Next, new an ExpressionDomain object and convert it to JSONObject. Using Json to pass data

Public void postByDefault () {ExpressionDomain expressionDomain=new ExpressionDomain ("hello", "hasaki", "win"); JSONObject jsonObj = (JSONObject) JSONObject.toJSON (expressionDomain); / / set request header HttpHeaders headers = new HttpHeaders (); headers.setContentType (MediaType.APPLICATION_JSON_UTF8); headers.add ("Accept", MediaType.APPLICATION_JSON.toString ()); / / request body HttpEntity formEntity = new HttpEntity (jsonObj.toString (), headers) / / initiate a request String jsonResult = restTemplate.postForObject ("http://localhost:8081/findDataByReflection", formEntity, String.class); / / parse the Json string into an object Response resp = JSON.parseObject (jsonResult, new TypeReference () {});}

Receiving end

Annotate a parameter with @ RequestBody to automatically parse Json as an object. The returned Response is also an object. If you add the @ ResponseBody annotation, the Json string will be returned. When parsing, parse the Json string into an object.

PostForEntity

The principle is the same as that of getForEntity, which we'll talk about below.

2.2getForObject method

GetForObject refers to the get request and returns an Object object. There are three ways.

2.2.1

By passing parameters through Map, you can use map to encapsulate the request parameter as the third parameter of getForObject, and modify the url as follows. "1" in map will replace {1} in url, and "2" will replace {2} in url.

Map map = new HashMap (); map.put ("1", "hello"); map.put ("2", "world"); String result = restTemplate.getForObject ("http://localhost:8081/getIds?param1={1}¶m2={2}", String.class,map)"

Interface side:

@ RequestMapping (value = "/ getIds", method = RequestMethod.GET) public @ ResponseBody String getIds (String param1, String param2) {return param1 + param2;}

2.2.2 through variable parameters

You can also directly put the value to be passed at the end of the parameter of the getForObject method, which replaces {1} and {2} sequentially. The interface code is still the same as 2.2.1.

String result = restTemplate.getForObject ("http://localhost:8081/getIds?param1={1}¶m2={2}", String.class,"hello", "world")

2.3getForEntity method

The use of getForEntity and getForObject is the same, except that the return result is a ResponseEntity that contains more response information, such as:

ResponseEntity response = restTemplate.getForEntity ("http://localhost:8081/getIds",String.class); response.getHeaders (); / / response header response.getStatusCode (); / / response code response.getBody (); / / response body, that is, the summary of the previous resultRestTemplate call interface)

First parameter: url address of the request

The second parameter: the type of result returned, where String.class indicates that the returned result is a string.

The third parameter: parameter value, which is in the form of Map and variable parameter.

The third parameter: the type of result returned, where String.class indicates that the returned result is a string.

The fourth parameter: parameter value, which is in the form of Map and variable parameters (usually not needed, the data is usually transferred in Json)

First parameter: url address of the request

The second parameter: actually HttpEntity, there are three main construction methods for this class, as follows

1. Create a new configuration class to configure the Bean of RestTemplate

Import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.http.client.ClientHttpRequestFactory;import org.springframework.http.client.SimpleClientHttpRequestFactory;import org.springframework.web.client.RestTemplate; / * RestTemplate configuration template * * @ author like * / @ Configurationpublic class RestTemplateConfig {@ Bean public RestTemplate restTemplate (ClientHttpRequestFactory factory) {return new RestTemplate (factory) } @ Bean public ClientHttpRequestFactory simpleClientHttpRequestFactory () {SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory (); factory.setReadTimeout (5000); / / in ms factory.setConnectTimeout (5000); / / in ms return factory;}}

Note: if you prompt in the compiler that factory cannot be injected automatically, it should conflict with other classes and have multiple ClientHttpRequestFactory

Just change the name of this factory to something else, for example, directly change it to simpleClientHttpRequestFactory here.

two。 Multiple ways to transmit and receive parameters

2.1postForObject method

PostForObject refers to the post request and returns an Object object.

New HttpEntity (request body)

New HttpEntity (request header)

New HttpEntity (request body, request header)

2.1.1 use Json to transmit and receive data

First introduce the pom configuration of fastJson

Com.alibaba fastjson 1.2.49

Inject RestTemplate into the implementation class

Next, new an ExpressionDomain object and convert it to JSONObject. Using Json to pass data

Public void postByDefault () {ExpressionDomain expressionDomain=new ExpressionDomain ("hello", "hasaki", "win"); JSONObject jsonObj = (JSONObject) JSONObject.toJSON (expressionDomain); / / set request header HttpHeaders headers = new HttpHeaders (); headers.setContentType (MediaType.APPLICATION_JSON_UTF8); headers.add ("Accept", MediaType.APPLICATION_JSON.toString ()); / / request body HttpEntity formEntity = new HttpEntity (jsonObj.toString (), headers) / / initiate a request String jsonResult = restTemplate.postForObject ("http://localhost:8081/findDataByReflection", formEntity, String.class); / / parse the Json string into an object Response resp = JSON.parseObject (jsonResult, new TypeReference () {});}

Receiving end

Annotate a parameter with @ RequestBody to automatically parse Json as an object. The returned Response is also an object. If you add the @ ResponseBody annotation, the Json string will be returned. When parsing, parse the Json string into an object.

PostForEntity

The principle is the same as that of getForEntity, which we'll talk about below.

2.2getForObject method

GetForObject refers to the get request and returns an Object object. There are three ways.

2.2.1

By passing parameters through Map, you can use map to encapsulate the request parameter as the third parameter of getForObject, and modify the url as follows. "1" in map will replace {1} in url, and "2" will replace {2} in url.

Map map = new HashMap (); map.put ("1", "hello"); map.put ("2", "world"); String result = restTemplate.getForObject ("http://localhost:8081/getIds?param1={1}¶m2={2}", String.class,map)"

Interface side:

@ RequestMapping (value = "/ getIds", method = RequestMethod.GET) public @ ResponseBody String getIds (String param1, String param2) {return param1 + param2;}

2.2.2 through variable parameters

You can also directly put the value to be passed at the end of the parameter of the getForObject method, which replaces {1} and {2} sequentially. The interface code is still the same as 2.2.1.

String result = restTemplate.getForObject ("http://localhost:8081/getIds?param1={1}¶m2={2}", String.class,"hello", "world")

2.3getForEntity method

The use of getForEntity and getForObject is the same, except that the return result is a ResponseEntity that contains more response information, such as:

ResponseEntity response = restTemplate.getForEntity ("http://localhost:8081/getIds",String.class); response.getHeaders (); / / response header response.getStatusCode (); / / response code response.getBody (); / / response body, that is, the previous resultRestTemplate call interface summary 1. This is the interface information @ PostMapping ("/ testm") public ReturnResult show11 (@ RequestParam ("id") String id, @ RequestParam ("name") String name) {System.out.println (id); UserInfo userInfo = userInfoMapper.selectByUserName (name); return ReturnResult.create (userInfo);}

This is the restTemplate call

/ / Post,@RequestParam---postForEntity @ Test public void sho11 () {String url = "http://127.0.0.1:8099/user/testm"; MultiValueMap request = new LinkedMultiValueMap (); request.add (" id "," 12324 "); request.add (" name "," nanc "); ResponseEntity resp = restTemplate.postForEntity (url, request, ReturnResult.class); ReturnResult body = resp.getBody () UserInfo data = body.getData (); System.err.println (data.getUserId ()); System.out.println (data);} 2. Interface

First parameter: url address of the request

The second parameter: the type of result returned, where String.class indicates that the returned result is a string.

The third parameter: parameter value, which is in the form of Map and variable parameter.

The third parameter: the type of result returned, where String.class indicates that the returned result is a string.

The fourth parameter: parameter value, which is in the form of Map and variable parameters (usually not needed, the data is usually transferred in Json)

First parameter: url address of the request

The second parameter: actually HttpEntity, there are three main construction methods for this class, as follows

Use RestTemplate to call interface 1. Create a new configuration class to configure RestTemplate's Beanimport org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.http.client.ClientHttpRequestFactory;import org.springframework.http.client.SimpleClientHttpRequestFactory;import org.springframework.web.client.RestTemplate; / * RestTemplate configuration template * * @ author like * / @ Configurationpublic class RestTemplateConfig {@ Bean public RestTemplate restTemplate (ClientHttpRequestFactory factory) {return new RestTemplate (factory) } @ Bean public ClientHttpRequestFactory simpleClientHttpRequestFactory () {SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory (); factory.setReadTimeout (5000); / / in ms factory.setConnectTimeout (5000); / / in ms return factory;}}

Note: if you prompt in the compiler that factory cannot be injected automatically, it should conflict with other classes and have multiple ClientHttpRequestFactory

Just change the name of this factory to something else, for example, directly change it to simpleClientHttpRequestFactory here.

two。 Multiple ways to transmit and receive parameters

2.1postForObject method

PostForObject refers to the post request and returns an Object object.

First parameter: url address of the request

The second parameter: actually HttpEntity, there are three main construction methods for this class, as follows

New HttpEntity (request body)

New HttpEntity (request header)

New HttpEntity (request body, request header)

The third parameter: the type of result returned, where String.class indicates that the returned result is a string.

The fourth parameter: parameter value, which is in the form of Map and variable parameters (usually not needed, the data is usually transferred in Json)

2.1.1 use Json to transmit and receive data

First introduce the pom configuration of fastJson

Com.alibaba fastjson 1.2.49

Inject RestTemplate into the implementation class

Next, new an ExpressionDomain object and convert it to JSONObject. Using Json to pass data

Public void postByDefault () {ExpressionDomain expressionDomain=new ExpressionDomain ("hello", "hasaki", "win"); JSONObject jsonObj = (JSONObject) JSONObject.toJSON (expressionDomain); / / set request header HttpHeaders headers = new HttpHeaders (); headers.setContentType (MediaType.APPLICATION_JSON_UTF8); headers.add ("Accept", MediaType.APPLICATION_JSON.toString ()); / / request body HttpEntity formEntity = new HttpEntity (jsonObj.toString (), headers) / / initiate a request String jsonResult = restTemplate.postForObject ("http://localhost:8081/findDataByReflection", formEntity, String.class); / / parse the Json string into an object Response resp = JSON.parseObject (jsonResult, new TypeReference () {});}

Receiving end

Annotate a parameter with @ RequestBody to automatically parse Json as an object. The returned Response is also an object. If you add the @ ResponseBody annotation, the Json string will be returned. When parsing, parse the Json string into an object.

PostForEntity

The principle is the same as that of getForEntity, which we'll talk about below.

2.2getForObject method

GetForObject refers to the get request and returns an Object object. There are three ways.

First parameter: url address of the request

The second parameter: the type of result returned, where String.class indicates that the returned result is a string.

The third parameter: parameter value, which is in the form of Map and variable parameter.

2.2.1

By passing parameters through Map, you can use map to encapsulate the request parameter as the third parameter of getForObject, and modify the url as follows. "1" in map will replace {1} in url, and "2" will replace {2} in url.

Map map = new HashMap (); map.put ("1", "hello"); map.put ("2", "world"); String result = restTemplate.getForObject ("http://localhost:8081/getIds?param1={1}¶m2={2}", String.class,map)"

Interface side:

@ RequestMapping (value = "/ getIds", method = RequestMethod.GET) public @ ResponseBody String getIds (String param1, String param2) {return param1 + param2;}

2.2.2 through variable parameters

You can also directly put the value to be passed at the end of the parameter of the getForObject method, which replaces {1} and {2} sequentially. The interface code is still the same as 2.2.1.

String result = restTemplate.getForObject ("http://localhost:8081/getIds?param1={1}¶m2={2}", String.class,"hello", "world")

2.3getForEntity method

The use of getForEntity and getForObject is the same, except that the return result is a ResponseEntity that contains more response information, such as:

ResponseEntity response = restTemplate.getForEntity ("http://localhost:8081/getIds",String.class); response.getHeaders (); / / response header response.getStatusCode (); / / response code response.getBody (); / / response body, that is, the previous resultRestTemplate call interface summary 1. This is the interface information @ PostMapping ("/ testm") public ReturnResult show11 (@ RequestParam ("id") String id, @ RequestParam ("name") String name) {System.out.println (id); UserInfo userInfo = userInfoMapper.selectByUserName (name); return ReturnResult.create (userInfo);}

This is the restTemplate call

/ / Post,@RequestParam---postForEntity @ Test public void sho11 () {String url = "http://127.0.0.1:8099/user/testm"; MultiValueMap request = new LinkedMultiValueMap (); request.add (" id "," 12324 "); request.add (" name "," nanc "); ResponseEntity resp = restTemplate.postForEntity (url, request, ReturnResult.class); ReturnResult body = resp.getBody () UserInfo data = body.getData (); System.err.println (data.getUserId ()); System.out.println (data);} 2. Interface @ GetMapping ("/ testp") public ReturnResult show22 (@ RequestParam String name, @ RequestParam Integer age, @ RequestParam String clazz) {System.out.println (name + "-" + age + "-" + clazz); UserInfo userInfo = userInfoMapper.selectByUserName (name); return ReturnResult.create (userInfo);}

Resttemplate

/ / Get, @ RequestParam-getForObject @ Test public void sho12 () {String url = "http://127.0.0.1:8099/rest/testp?name={name}&age={age}&clazz={clazz}"; Map map = new HashMap (); map.put (" name "," nanc "); map.put (" age ", 34); map.put (" clazz "," 12 ") ReturnResult forObject = restTemplate.getForObject (url, ReturnResult.class, map); UserInfo data = forObject.getData (); System.out.println (data);} "how SpringBoot uses RestTemplate to call the interface" ends here, thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

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.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report