“This is the 8th day of my participation in the Gwen Challenge in November. Check out the details: The Last Gwen Challenge in 2021”

Most microservices communicate with each other using HTTP, which naturally requires the use of HttpClient. Before Spring is not available, Apache HttpClient and Ok HttpClient are commonly used, but once Spring is introduced, there is a better option – RestTemplate.

Interface:To accept a Form request, read the two parameters para1 and para2 defined by the Form and return them to the client as a response.

After defining the interface, use the RestTemplate to send one of these form requests as shown in the following code example:The above code defines a Map with two form parameters, and then submits the form using the postForObject of the RestTemplate. Error 400 is displayed in executing code, i.e. request error:Is missing the para1 form parameter, why?

parsing

The form submitted by RestTemplate looks like the final submitted request. Wireshark caught:We’re actually submitting the defined form data as JSON, so our interface processing doesn’t get any form parameters. According to? How to submit data as a JSON request body? Note that RestTemplate executes the call stack:Eventually, the Jackson tool was used to serialize the formThe key reason to use JSON is in

RestTemplate.HttpEntityRequestCallback#doWithRequest

Iterates through all currently supported codecs based on the current Body content to commit:

  • If a suitable codec is found, use it to complete the Body transformation

See if the JSON codec is appropriate

AbstractJackson2HttpMessageConverter#canWrite

As you can see, JSON serialization is possible when the Body is a HashMap. So the form is then serialized as the request Body.

But I still wonder, why not codecs adapted to form processing? It is up to the codec to determine whether the implementation is supported:

FormHttpMessageConverter#canWrite

You can see that the form can only be submitted if the Body we send is MultiValueMap. The original RestTemplate submission form must be MultiValueMap! Our example defines a normal HashMap, which is ultimately sent as a Body request.

correction

Use MultiValueMap to store form data:After the fix, the form data is eventually encoded using the following code:

FormHttpMessageConverter#write

The screenshot of the sent data is as follows:That’s right! In fact, the official document also states:

Reference:

  • Docs. Spring. IO/spring – fram…