Spring's client access to restful business

Source: Internet
Author: User
Tags connection pooling naming convention vars

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
  1. String uri = "Http://example.com/hotels/1/bookings";
  2. Postmethod post = new Postmethod (URI);
  3. String request = //create booking request content
  4. Post.setrequestentity (new stringrequestentity (request));
  5. Httpclient.executemethod (POST);
  6. if (httpstatus.sc_created = = Post.getstatuscode ()) {
  7. Header location = Post.getrequestheader ("location");
  8. if (location! = null) {
  9. System.out.println ("Created new booking at:" + location.getvalue ());
  10. }
  11. }

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
    1. String result = Resttemplate.getforobject (
    2. "Http://example.com/hotels/{hotel}/bookings/{booking}", String.  class,"a", " 21");

The variable length parameters used above,

[Java]View Plaincopy
    1. map<string, string> VARs = Collections.singletonmap ("Hotel", "42");
    2. String result = Resttemplate.getforobject (
    3. "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
    1. URI = "Http://example.com/hotels/{id}/bookings";
    2. Resttemplate template = new Resttemplate ();
    3. Booking Booking = //Create Booking Object
    4. 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
    1. 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
    1. HttpClient HttpClient = Httpclientbuilder.create (). build ();
    2. Clienthttprequestfactory requestfactory = new Httpcomponentsclienthttprequestfactory (httpClient);
    3. Resttemplate resttemplate = new Resttemplate (requestfactory);


The generic callback interface is requestcallback and is called when the execution method is called

[Java]View Plaincopy
    1. Public <T> T execute (String URL, HttpMethod method, Requestcallback Requestcallback,
    2. Responseextractor<t> responseextractor, String ... urlvariables)
    3. Also have an overload with Urlvariables as a map<string, string>.


The Requestcallback interface is defined as follows:

[Java]View Plaincopy
    1. Public interface Requestcallback {
    2. void Dowithrequest (Clienthttprequest request) throws IOException;
    3. }

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
    1. 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
    1. UriComponents uricomponents = uricomponentsbuilder.fromuristring (
    2. "Http://example.com/hotels/{hotel}/bookings/{booking}"). Build ()
    3. . Expand ("a", " a")
    4. . Encode ();
    5. Uri uri = Uricomponents.touri ();

Or specify each URI component individually:

[Java]View Plaincopy
    1. UriComponents uricomponents = Uricomponentsbuilder.newinstance ()
    2. . Scheme ("http"). Host ("example.com"). Path ("/hotels/{hotel}/bookings/{booking}"). Build ()
    3. . Expand ("a", " a")
    4. . Encode ();
    5. 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
  1. Httpheaders requestheaders = new Httpheaders ();
  2. Requestheaders.set ("Myrequestheader", "myvalue");
  3. httpentity<?> requestentity = new Httpentity (requestheaders);
  4. httpentity<string> response = Template.exchange (
  5. "Http://example.com/hotels/{hotel}",
  6. Httpmethod.get, Requestentity, String.  class, "42");
  7. String Responseheader = Response.getheaders (). GetFirst ("Myresponseheader");
  8. 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
    1. Jacksonserializationvalue JSV = new Jacksonserializationvalue (new User ("Eric", "7!jd#h23"),
    2. User.withoutpasswordview.  class);
    3. httpentity<jacksonserializationvalue> entity = new httpentity<jacksonserializationvalue> (JSV);
    4. 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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.