Spring Conversion Magic

robin :

I am having a piece of code like below for calling one of our service.

MultiValueMap<String, String> parametersMap = new LinkedMultiValueMap<>();
            parametersMap.add("query", query);
            parametersMap.add("locale", "en_US");
            parametersMap.add("resultsLimit", Boolean.FALSE.toString());
            parametersMap.add("maxResults", maxResults);
            parametersMap.add("type", "TTT");
            parametersMap.add("ids", commaSeparatedValues(ids));
            parametersMap.add("infoTypes", "HHH,JJJ");
            HttpEntity<MultiValueMap<String, String>> httpEntity = new HttpEntity<>(parametersMap, getHttpHeaders());
            MyEntity myEntity = restTemplate.postForEntity("http://example.com", httpEntity, MyEntity.class);

And at the server side the controller code is like

    @RequestMapping("my/service")
                public MyEntity suggest(@RequestParam(required = true) String query, @RequestParam(required = true) String locale,
@RequestParam(required = false) String resultsLimit, @Valid OtherOptions options) 

and the OtherOption class is like

class OtherOptions {
              String maxResults;
              String type;
              String ids;
              String infoTypes;
            }

Here everything is working fine, but I am confused about somethings like .

  1. Is it a get or post request ?
  2. How is some of the parameter maps content become request params(query params) and some others got mapped to the Object of OtherOptions ?
  3. Which is the actual body of the request ?
Kavithakaran Kanapathippillai :
  1. Is it a get or post request ?

    It is a post request. you are calling restTemplate.postForEntity. But your server side method is not restricted as you didn't specify the method attribute for RequestMapping so same method can handle any http method from the point of server.

  2. How is some of the parameter maps content become request params(query params) and some others got mapped to the Object of OtherOptions?

    None of them are query params. See the spring docs for the meaning of @RequestParam. In your case, it all comes from body and not as query params

    https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/bind/annotation/RequestParam.html

    https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/client/RestTemplate.html#postForEntity-java.net.URI-java.lang.Object-java.lang.Class-

    The body of the entity, or request itself, can be a MultiValueMap to create a multipart request.

  3. Which is the actual body of the request?

    parametersMap is the body of the http request.

Note: Currently your call should fail because you are posting it to http://example.com at client and listening at server side on my/service

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related