In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly explains "RestTemplate how to send a GET request with headers". The content of the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "RestTemplate how to send a GET request with headers".
RestTemplate sends a GET request with headers
Requirement: send a GET request for a custom header, and a signature needs to be inserted into the header.
Send a POST request for a custom header
I've written a similar request before, but it's from POST. This has also been touched for a period of time, and I have seen the whole parameters for myself. The code is as follows:
/ / header fill LinkedMultiValueMap headers = new LinkedMultiValueMap (); headers.put ("Content-Type", Collections.singletonList ("application/json;charset=UTF-8")); headers.put ("signature", Collections.singletonList (makeSignature (form.getNewMobile (); / / body fill JSONObject json = new JSONObject (); json.put ("oldMobile", mobile); json.put ("newMobile", form.getNewMobile ()); HttpEntity request = new HttpEntity (json.toString (), headers) / / A singleton restTemplateRestTemplate restTemplate = HttpInvoker.getRestTemplate (); / / send a request ResponseEntity response = restTemplate.postForEntity (whiteListURL, request, String.class)
It's simple to think that you just need to change the above postForEntity () to get, but that's not the case.
Update: 2019-12-11
Learned a more friendly way to write from links:
Private static void getEmployees () {final String uri = "http://localhost:8080/springrestexample/employees"; RestTemplate restTemplate = new RestTemplate (); HttpHeaders headers = new HttpHeaders (); headers.setAccept (Arrays.asList (MediaType.APPLICATION_JSON)); HttpEntity entity = new HttpEntity (" parameters ", headers); ResponseEntity result = restTemplate.exchange (uri, HttpMethod.GET, entity, String.class); System.out.println (result);}
After a cursory look at the implementation of the postForEntity () and getForEntity () methods, both prepare the parameters, and then call the execute () method, as follows:
/ / POST@Overridepublic ResponseEntity postForEntity (String url, @ Nullable Object request, Class responseType, Object...) UriVariables) throws RestClientException {RequestCallback requestCallback = httpEntityCallback (request, responseType); ResponseExtractor responseExtractor = responseEntityExtractor (responseType); return nonNull (execute (url, HttpMethod.POST, requestCallback, responseExtractor, uriVariables);} / / GET@Override@Nullablepublic T getForObject (String url, Class responseType, Map uriVariables) throws RestClientException {RequestCallback requestCallback = acceptHeaderRequestCallback (responseType); HttpMessageConverterExtractor responseExtractor = new HttpMessageConverterExtractor (responseType, getMessageConverters (), logger) Return execute (url, HttpMethod.GET, requestCallback, responseExtractor, uriVariables);}
The difference is that when RequestCallback is instantiated, the parameters passed are different. When you POST, you pass header as an argument to RequestCallback. Then the GET and POST parameters in execute () are not the same. By this time, it is obvious to send a GET request for a custom header.
The instantiated functions are all public.
If it is not public, or we cannot access it directly, we can also consider calling the relevant method through reflection, but there is no need to use reflection here.
Results / / header is populated with LinkedMultiValueMap headers = new LinkedMultiValueMap (); headers.put ("Content-Type", Collections.singletonList ("application/json;charset=UTF-8")); headers.put ("signature", Collections.singletonList (makeSignature (mobile); / / get singleton RestTemplateRestTemplate restTemplate = HttpInvoker.getRestTemplate (); HttpEntity request = new HttpEntity (headers); / / parameters needed to construct execute () execution. RequestCallback requestCallback = restTemplate.httpEntityCallback (request, JSONObject.class); ResponseExtractor responseExtractor = restTemplate.responseEntityExtractor (JSONObject.class); / / execute execute (), send the request ResponseEntity response = restTemplate.execute (apiAddress + "/ xxx/whitelist/check?phone=" + mobile, HttpMethod.GET, requestCallback, responseExtractor)
Although it is very simple, it seems impossible, but I have done it and finished it, and I have a great sense of achievement.
RestTemplate gracefully sends Get requests
In our project, if we send a Get request with parameters through RestTemplate, we can piece together the url by concatenating strings, such as the following:
String url = "http://127.0.0.1:8080/rest/get?name="+ name +" & id= "+ id;ResponseEntity forEntity = restTemplate.getForEntity (url, RestVO.class)
However, this approach is not very elegant, and we can also send Get requests in the following ways
Method 1: use placeholders String url = "http://127.0.0.1:8080/rest/path/{name}/{id}";Map params = new HashMap (); params.put (" name "," this is name "); params.put (" id ", 1L); ResponseEntity forEntity = restTemplate.getForEntity (url, RestVO.class, params)
The key of Map should be consistent with the placeholder in url
Mode 2: use LinkedMultiValueMap and UriComponentsBuilderString url = "http://127.0.0.1:8080/rest/get";MultiValueMap params = new LinkedMultiValueMap (); params.add (" name "," this is name "); params.add (" id "," 1 "); UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl (url); URI uri = builder.queryParams (params). Build (). Encode (). ToUri (); ResponseEntity forEntity = restTemplate.getForEntity (uri, RestVO.class); return forEntity.getBody ()
Mode 2 looks the most elegant, separating the parameter settings from the url.
Thank you for your reading, the above is the content of "how RestTemplate can send GET requests with headers". After the study of this article, I believe you have a deeper understanding of how RestTemplate sends GET requests with headers, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!
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.