http://blog.csdn.net/yiifaa/article/details/77939282
**********************************************
In the design of rest interface, it is a common method to use Resttemplate for interface test, but in the process of using, because of its many parameters, many students confuse the difference between form submission and payload submission, and the interface design differs from the traditional way of submitting the browser. , there are often a variety of errors, such as 405 errors, or no data submitted at all, the error sample is as follows:
Exception in thread ' main ' org.springframework.web.client.httpclienterrorexception:405 Method not allowed at Org.springframework.web.client.DefaultResponseErrorHandler.handleError (defaultresponseerrorhandler.java:63) At org.springframework.web.client.RestTemplate.handleResponse (resttemplate.java:700) at Org.springframework.web.client.RestTemplate.doExecute (resttemplate.java:653) at Org.springframework.web.client.RestTemplate.execute (resttemplate.java:613) at Org.springframework.web.client.RestTemplate.exchange (resttemplate.java:531)
1. Submit with the Exchange method
Exchange can perform both the Post method and the get, so the application is the most extensive and uses the following methods:
String url = "Http://localhost/mirana-ee/app/login"; Resttemplate Client=Newresttemplate (); Httpheaders Headers=Newhttpheaders ();//do not easily change this submission method, most of the cases, the submission method is the form submissionHeaders.setcontenttype (mediatype.application_form_urlencoded);//package parameters, do not replace with map and hashmap, otherwise parameters cannot be passedMultivaluemap<string, string> params=NewLinkedmultivaluemap<string, string>();//also supports ChineseParams.add ("username", "User name");p Arams.add ("Password", "123456"); Httpentity<multivaluemap<string, string>> requestentity =NewHttpentity<multivaluemap<string, string>>(params, headers);//executing an HTTP requestresponseentity<string> response = Client.exchange (URL, httpmethod.post, requestentity, String.class);//Output ResultsSystem.out.println (Response.getbody ());
2. Submit with Postforentity
Postforentity is a simplification of exchange, just to reduce the httpmethod.post parameter, as follows:
// The above code is exactly the same // only need to replace the Exchange method responseentity<string> response = Client.postforentity (URL, requestentity, String. Class );
3. Differences between form submissions and payload submissions
In the controller's method parameters, if the "@ModelAttribute" is changed to "@RequestBody" annotation, then the submission method is payload, the details of the differences are described in the summary of the use of $.ajax (i) : Form submission and payload submission, code examples are as follows:
// Please note that the @requestbody annotation @RequestMapping (value= "/login", Method=requestmethod.post, consumes= "application/ JSON ")// do not add @modelattribute to the lily, otherwise it will be overwritten, as follows //public account Getaccount (@[email protected] account account) public account Getaccount (@RequestBody account account) { account.setversion (new Date ()); return Account ;}
Once again, never add the "@ModelAttribute" again because it has a higher priority, so the system will parse the submission in form.
For the payload method, the submitted content must be string, and the header to be set to "Application/json", the example is as follows:
//Request AddressString url = "Http://localhost/mirana-ee/app/login"; Resttemplate Client=Newresttemplate ();//Be sure to set the headerHttpheaders headers =Newhttpheaders (); Headers.setcontenttype (Mediatype.application_json_utf8);//converts the submitted data to a string//the best way to get Objectmapper is through bean injection.Objectmapper mapper =NewObjectmapper (); Map<string, string> params=maps.newhashmap ();p arams.put ("Username", "Inter");p Arams.put ("Password", "123456"); String value=mapper.writevalueasstring (params); Httpentity<String> requestentity =NewHttpentity<string>(value, headers);//executing an HTTP requestresponseentity<string> response = client.postforentity (URL, requestentity, String.class ); System.out.println (Response.getbody ());
If the content is not committed as a string, the following error must be present:
Exception in thread ' main ' org.springframework.web.client.httpclienterrorexception:400 bad Request at Org.springframework.web.client.DefaultResponseErrorHandler.handleError (defaultresponseerrorhandler.java:63) At org.springframework.web.client.RestTemplate.handleResponse (resttemplate.java:700) at Org.springframework.web.client.RestTemplate.doExecute (resttemplate.java:653) at Org.springframework.web.client.RestTemplate.execute (resttemplate.java:613) at Org.springframework.web.client.RestTemplate.postForEntity (resttemplate.java:407)
Finally, it should be stressed that through @requestbody is unable to obtain the request parameters, such as the above service side of the code to the following format, you will not get the data, but the form submission is the opposite.
@RequestMapping (value= "/login", consumes= "Application/json", method=requestmethod.post) Public Account Getaccount (@RequestBody account, HttpServletRequest request) { // The parameter value System.out.println (Request.getparameter ("username") must not be reached; Account.setversion (new Date ()); return Account ;}
4. Structure of the Httpentity
Httpentity is the encapsulation of the HTTP request, which consists of two parts, header and Body,header for setting the request header, and body for setting the request body, so its constructor is as follows:
// value is the request body / header for the request header new httpentity<string> (value, headers);
5. Httpentity and Urivariables
In the use of Resttemplate, httpentity is used to pass specific parameter values, while Urivariables is used to format the HTTP address instead of the address parameter, the correct usage is as follows:
// Add a format parameter to the address pathString url = "Http://localhost/mirana-ee/app/{path}"; // Prepare the format parameter map<string, string> varparams = maps.newhashmap (); Varparams.put ("path", "Login" ); // Other code slightly // formatted submit address responseentity<string> response = Client.postforentity (URL, requestentity, String. Class, Varparams);
6. Notes on Httpmessageconverter
In many of the online examples, I have found that many people have added custom Httpmessageconverter to handle payload submissions, as follows:
// There is absolutely no need to Client.getmessageconverters (). Add (new mappingjackson2httpmessageconverter ()); Client.getmessageconverters (). Add (new stringhttpmessageconverter ());
Then, after I look at the source and debugging found, Resttemplate built up 7 kinds of httpmessageconverter, as follows:
1. Org.springframework.http.converter.ByteArrayHttpMessageConverter
2. Org.springframework.http.converter.StringHttpMessageConverter
3. Org.springframework.http.converter.ResourceHttpMessageConverter
4. Org.springframework.http.converter.xml.SourceHttpMessageConverter
5. Org.springframework.http.converter.support.AllEncompassingFormHttpMessageConverter
6. Org.springframework.http.converter.xml.Jaxb2RootElementHttpMessageConverter
7. Org.springframework.http.converter.json.MappingJackson2HttpMessageConverter
"'
Conclusion
Resttemplate can greatly simplify the submission of form data, and comes with the ability to automatically convert JSON data, but only understand the httpentity structure (header and body), and understand the difference between the urivariables and To really master its usage.
Spring Boot (iii): Resttemplate three ways to submit form data