Spring's client access to restful business
Resttemplate is the core class of client access to restful business. Conceptually similar to other spring template classes, such as JdbcTemplate and Jmstemplate. The behavior of resttemplate can be customized by providing a callback method and configuration Httpmessageconverter (used to package the object into the HTTP request body and extract it from the returned response to an object). Because XML is generally used as a message format, Spring provides a framework for Marshallinghttpmessageconverter to use objects to XML, which is part of the ORG.SPRINGFRAMEWORK.OXM package. This is for you. mapping XML to Objects provides a broad selection.
This section describes how to use Resttemplate and its associated httpmessageconverters.
21.10.1 resttemplate
Calling restful business in Java typically uses an auxiliary class, such as Apache's httpcomponents HttpClient. For normal rest operations, this is a very low-level approach.
[Java]View Plaincopy
- String uri = "Http://example.com/hotels/1/bookings";
- Postmethod post = new Postmethod (URI);
- String request = //create booking request content
- Post.setrequestentity (new stringrequestentity (request));
- Httpclient.executemethod (POST);
- if (httpstatus.sc_created = = Post.getstatuscode ()) {
- Header location = Post.getrequestheader ("location");
- if (location! = null) {
- System.out.println ("Created new booking at:" + location.getvalue ());
- }
- }
Resttemplate provides an advanced method that corresponds to six main HTTP methods, which makes it possible to invoke restful business in one line and perform rest best practices.
Note: Resttemplate also has an asynchronous section.
Resttemplate Method Review Table
HTTP method Resttemplate method
Delete Delete
GET getforobjectgetforentity
HEAD headforheaders (String url,string ... Urlvariables)
OPTIONS optionsforallow (String url,string ... Urlvariables)
POST postforlocation (String url,object request,string ... Urlvariables) postforobeject (String url,object request,class<t> responsetype,string...urivariables)
Put put (String url,object reuqest,string...urlvariables)
PATCH and others Exchange execute
the name of the Resttemplate method follows a naming convention, the first part specifies what HTTP method is called, and the second part indicates the return value. For example,the Getforobject () method executes a GET and converts the HTTP response to the type of object you want and returns the object. The Postforlocation () method performs a post operation that converts the given object to an HTTP request and returns the location header of the HTTP response, where the most recent object can be found. The restclientexception exception type is thrown in case of exception handling for HTTP requests, and you can change the behavior of this exception handling by inserting the Responseerrorhandler implementation into resttemplate.
The Exchange and Execute methods are generalized versions of the methods specified in the preceding list and support other combinations and methods, such as HTTP patches. However, the underlying HTTP must also support the desired union. The httpurlconnection of the JDK does not support patch methods, but the version 4.2 or later of Apache Httpcomponents HttpClient is supported. They also allow Resttemplate to read HTTP responses to a generic type (such as list<account>), using a parameterizedtypereference, which is a new class for fetching and passing general type information.
The objects passed to these methods and the objects returned from these methods are converted by Httpmessageconverter instances and converted from messages. The main types of converters are registered by default, but you can also encapsulate your own converters and register with the bean properties of messageconverters (). The default converter instance registered with this template is Bytearrayhttpmessageconverter,stringhttpmessageconverter, Formhttpmessageconverter and Sourcehttpmessageconverter. You can use the Messageconverters () Bean property to override these default, In particular, rewriting is necessary when using Marshallinghttpmessageconverter or Mappingjackson2httpmessageconverter.
Each method passes the URI template parameter in two ways, either the String variable length parameter, or MAP<STRING,STRING> For example:
[Java]View Plaincopy
- String result = Resttemplate.getforobject (
- "Http://example.com/hotels/{hotel}/bookings/{booking}", String. class,"a", " 21");
The variable length parameters used above,
[Java]View Plaincopy
- map<string, string> VARs = Collections.singletonmap ("Hotel", "42");
- String result = Resttemplate.getforobject (
- "Http://example.com/hotels/{hotel}/rooms/{hotel}", String. class, VARs);
This is used by MAP<STRING,STRING>.
To create a resttemplate instance, you can call only the default constructor. This will use the standard Java classes from the java.net package to implement the underlying implementation of the HTTP request. This can be overridden by specifying the clienthttprequestfactory implementation. Spring provides the Httpcomponentsclienthttprequestfactory factory class, which uses the Apache httpcomponents HttpClient to create the request. Httpcomponentsclienthttprequestfactory uses the Org.apache.http.client.HttpClient instance configuration, which in turn uses the certificate information or the connection pooling feature configuration.
Attention:
When java.net implements an HTTP request, it can produce an exception that represents an error when the response state is accessed. If this is a problem, switch to using httpcomponentsclienthttprequestfactory
The previous example uses Apache HttpcomponentsHttpClient直接重写,并使用下面显示的RestTemplate:
[Java]View Plaincopy
- URI = "Http://example.com/hotels/{id}/bookings";
- Resttemplate template = new Resttemplate ();
- Booking Booking = //Create Booking Object
- URI location = template.postforlocation (URI, booking, "1");
To use Apache httpcomponents instead of the native java.net feature, construct the following resttemplate:
[Java]View Plaincopy
- Resttemplate template = new Resttemplate (new Httpcomponentsclienthttprequestfactory ());
Note: Apache httpclient supports gzip encoding. To use it, the Httpcomponentsclienthttprequestfactory factory class is constructed, as follows:
[Java]View Plaincopy
- HttpClient HttpClient = Httpclientbuilder.create (). build ();
- Clienthttprequestfactory requestfactory = new Httpcomponentsclienthttprequestfactory (httpClient);
- Resttemplate resttemplate = new Resttemplate (requestfactory);
The generic callback interface is requestcallback and is called when the execution method is called
[Java]View Plaincopy
- Public <T> T execute (String URL, HttpMethod method, Requestcallback Requestcallback,
- Responseextractor<t> responseextractor, String ... urlvariables)
- Also have an overload with Urlvariables as a map<string, string>.
The Requestcallback interface is defined as follows:
[Java]View Plaincopy
- Public interface Requestcallback {
- void Dowithrequest (Clienthttprequest request) throws IOException;
- }
Allows you to manipulate the request header and write it into the request body. When using the Execute method, you do not have to worry about any resource management, and the template will always close the request and handle any errors.
Using the URI working with URI
For each major HTTP method, Resttemplate provides a string type URI or a variable of the Java.net.URI instance as the first argument.
The string URI variable accepts a template argument as a String variable length parameter or as a map<string,string>. They also assume that the URL string type is not encoded and needs to be encoded. Examples are as follows:
[Java]View Plaincopy
- Resttemplate.getforobject ("Http://example.com/hotel list", String. Class);
A GET request will be executed on the http://example.com/hotel%20list. This means that if you enter a string of the encoded URL, it will be encoded again. That http://example.com/hotel%20list will be turned intohttp://example.com/hotel%2520list。如果这不是我们想要的结果,使用java.net.URI方法变量,其假设已经编码的url是有用的,如果你想多次使用一个单一的URI。
UriComponentsBuilder这个类能用于构建和编码URI,包括支持URI模板。例如,你可以以一个String类型的url开始。
[Java]View Plaincopy
- UriComponents uricomponents = uricomponentsbuilder.fromuristring (
- "Http://example.com/hotels/{hotel}/bookings/{booking}"). Build ()
- . Expand ("a", " a")
- . Encode ();
- Uri uri = Uricomponents.touri ();
Or specify each URI component individually:
[Java]View Plaincopy
- UriComponents uricomponents = Uricomponentsbuilder.newinstance ()
- . Scheme ("http"). Host ("example.com"). Path ("/hotels/{hotel}/bookings/{booking}"). Build ()
- . Expand ("a", " a")
- . Encode ();
- Uri uri = Uricomponents.touri ();
Processing of request and response headers
In addition to the methods described above, Resttemplate also has the Exchange () method, which can be used for the execution of any HTTP method based on the Httpentity class.
Perhaps more importantly, the Exchange () method can be used to add requests and response headers. For example:
[Java]View Plaincopy
- Httpheaders requestheaders = new Httpheaders ();
- Requestheaders.set ("Myrequestheader", "myvalue");
- httpentity<?> requestentity = new Httpentity (requestheaders);
- httpentity<string> response = Template.exchange (
- "Http://example.com/hotels/{hotel}",
- Httpmethod.get, Requestentity, String. class, "42");
- String Responseheader = Response.getheaders (). GetFirst ("Myresponseheader");
- String BODY = Response.getbody ();
In the above example, we first prepared a request that contained the Myrequestheader header information. Later we retrieved the corresponding response and read the Myresponseheader and the message body.
Jackson JSON View Support
A subset of the properties of the Jackson JSON view serialization object may be specified. For example:
[Java]View Plaincopy
- Jacksonserializationvalue JSV = new Jacksonserializationvalue (new User ("Eric", "7!jd#h23"),
- User.withoutpasswordview. class);
- httpentity<jacksonserializationvalue> entity = new httpentity<jacksonserializationvalue> (JSV);
- string s = Template.postforobject ("Http://example.com/user", Entity, String. Class);
This article transferred from: http://blog.csdn.net/luccs624061082/article/details/40893963
Spring's client access to restful business