Spring Resttemplate Detailed

Source: Internet
Author: User
Tags finally block soap string format

1. What is rest?

REST (Representationalstate Transfer) is a noun presented by Roy Fielding describing the architectural style of an interconnected system. Rest defines a set of architectural principles that you can use to design a system-resource-centric Web service, including how clients written in different languages process and transfer resource state over HTTP.

Why is it called REST? The web is essentially composed of a variety of resources, and the resource is uniquely identified by the URI. The browser (or any other browser-like application) will show a representation of the resource, or a performance state. If a user directs a link to another resource on the page, the resource is accessed and its status is displayed. This means that the client application has a state transition, which is called rest, depending on the state of each resource's performance.

Attached: rest definition, rest versus soap comparison

2. Four levels of rest maturity

The first-level (LEVEL0) Web service only uses HTTP as a transport, and is actually a specific form of a remote method call (RPC). Both soap and XML-RPC belong to this class .

A second level (LEVEL1) Web service introduces the concept of resources. Each resource has a corresponding identifier and expression.

The third level (LEVEL2) Web service uses different HTTP methods for different operations and uses HTTP status codes to represent different results. such as the HttpGet method to get the resource, Httpdelete method to delete the resource.

A fourth level (LEVEL3) Web service uses HATEOAS. The link information is included in the expression of the resource. The client can discover the actions that can be performed based on the link.

The third level establishes a one-to-a mapping between create, read, update, and delete (Create,read, update, and Delete,crud) operations and HTTP methods. Based on this mapping:

(1) To create a resource on the server, you should use the Post method.

(2) to retrieve a resource, you should use the Get method.

(3) To change the state of a resource or update it, you should use the Put method.

(4) To delete a resource, you should use the Delete method.

3. HTTP request method

(1) Get: Get resources by requesting URIs
(2) POST: for adding new content
(3) PUT: Used to modify a content, if it does not exist add
(4) Delete: Delete a content
(5) OPTIONS: Ask what methods you can perform
(6) HEAD: Similar to get, but does not return body information for checking the existence of objects and getting the object's metadata
(7) CONNECT: For the agent to transfer, such as the use of SSL
(8) TRACE: For remote diagnostics server

4. Status code for HTTP request

(1) Successful successful2xx: This type of status code identifies the client's request to be successfully received, understood, and accepted. Common such as (OK), 204 (nocontent).
(2) REDIRECT redirection3xx: The status code for this category identifies the user agent to make further actions to complete the request. Common such as 301 (movedpermanently), 302 (movedtemprarily).
(3) Client error The status code of the 4XX:4XX category is used when the client is like an error. Common (Badrequest), 401 (Unauthorized), 403 (Forbidden), 404 (NotFound).
(4) Server error 5XX: The response status code starts with 5 indicating that the server knows it has made an error or is not capable of executing the request. Common (Internalserver Error), 502 (Badgateway), 504 (gatewaytimeout).

Standard Introduction to HTTP1.1: http://blog.chinaunix.net/uid-9188830-id-2007021.html



5, RestTemplate5.1 Introduction

Spring ' Scentral class for synchronous client-side HTTP access. It simplifies communication with httpservers, and enforces RESTful principles. Ithandles HTTP connections, leaving application code to provide URLs (with possible template variables) andextract results.

Simply put: It simplifies the process of initiating HTTP requests and processing responses, and supports rest. Why is that simplified?

Look at two ways to implement

(1) Establish a connection using the URLConnection under the java.net package

String result= ""; Bufferedreaderin=NULL; Try{String urlnamestring= URL + "?" +param; URL Realurl=NewURL (urlnamestring); //opening and linking between URLsUrlconnectionconnection =realurl.openconnection (); //to set common request propertiesConnection.setrequestproperty ("Accept", "*/*"); Connection.setrequestproperty ("Connection", "keep-alive"); Connection.setrequestproperty ("User-agent",                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1) "); //establish an actual connectionConnection.connect (); //Get all response header fieldsmap<string,list<string>> map =Connection.getheaderfields (); //iterate through all the response header fields             for(String key:map.keySet ()) {System.out.println (key+ "--->" +Map.get (key)); }            //defines the response of the BufferedReader input stream to read the URLin =NewBufferedReader (Newinputstreamreader (Connection.getinputstream ()));            String Line;  while(line = In.readline ())! =NULL) {result+=Line ; }        } Catch(Exception e) {...} //Use the finally block to close the input stream        finally{         //Close the stream}

(2) using Resttempalte

Responseentity<ssourlprm>result = Resttemplate.getforentity (REQUESTPATHURL,SSOURLPRM.  Class);  
5.2 Interface for opening up

(1)

DELETE Delete
GET Getforobject
Getforentity
HEAD Headforheaders
OPTIONS Optionsforallow
POST Postforlocation
Postforobject
PUT Put
Any Exchange
Execute

(2) Each small class is divided into three kinds, what is the difference between these three kinds? * The first and second parameters are all string representations of a URI. But their last parameter is object[] and map* the first parameter of the third type uses Java.net.URI to represent a URI. And only two of the parameters

This is because a URI of type string supports placeholders. Like what:

Resttemplate.getforobject ("http://example.com/hotels/{hotel}/bookings/{booking}", String.class, "42", "21");

Then the URI of the final access is: HTTP://EXAMPLE.COM/HOTELS/42/BOOKINGS/21

But the string has a small flaw: The URI in string form will be encoded two times (URL encode Baidu), this requires the server to get the URI parameters when the active decoding, but if the service provider does not do so?

Then you need to use a java.net.URI that doesn't use any coding.

PS: Parameter ' class<t> responsetype' defines the type of the returned data.

(3) Exchange differs from other interfaces:

> Allow callers to specify methods for HTTP requests (Get,post,put, etc.)

> can add body and header information to the request, and its contents are described by the parameter ' httpentity<?>requestentity '

>exchange supports the ' parameter-containing type ' (that is, the generic class) as the return type, which is described by ' parameterizedtypereference<t>responsetype '. Like what:

New arraylist<string>new parameterizedtypereference<arraylist<string>>() {}; System.out.println (Pt.gettype ());

The resulting results are:

class java.util.ArrayListjava.util.AbstractList<E>java.util.ArrayList<java.lang.string >
* This is because Parameterizedtypereference<arraylist<string>> uses Getgenericsuperclass () instead of actual arguments. Method gets the type of its parent class (note that the new here has curly braces, which is a subclass of Parameterizedtypereference), The type of the parent class is described by Java.lang.reflect.Type, and then the argument type of the parent class is obtained through the type's getactualtypearguments (), noting that the resulting type class is not of the class class.

(4) Excute all the Get, post, delete, put, options, head, and exchange methods are finally called the Excute method. Give me a chestnut:
@Override  public <T> T getforobject (String url, class<t>     throws     restclientexception {  =     acceptheaderrequestcallback (responsetype);  Httpmessageconverterextractor<T> responseextractor =<span style= "White-space:pre" >    </ span>New httpmessageconverterextractor<t>(Responsetype, Getmessageconverters (), logger);   return  execute (URL, httpmethod.get, Requestcallback, Responseextractor, urlvariables);}
The Excute method simply turns the URI of the string format into Java.net.URI and then calls the Doexecute method. The entire calling process
6.doexcute6.1 definition
protected throws restclientexception {...}

There are two classes to know: Requestcallback &responseextractor 6.2 requestcallback
Callback interface for code, operates on a clienthttprequest. Allows to manipulate the request headers, and write to the request body.
Simply stated: Used to manipulate the request header and body, executed before the request is issued.

The interface has two implementation classes:
Acceptheaderrequestcallback Only the request headers are processed for the GetXXX () method.
Httpentityrequestcallback Inheriting from Acceptheaderrequestcallback can handle the request header and body for the putxxx (), postxxx (), and Exchange () methods.

* DELETE, HEAD, options do not use this interface.
6.3 Initiating the request 6.4 ResponseExtractor6.4.1 definition generic callback interface used by Resttemplate ' s retrieval methods implementations Of this interface perform the actual work of extracting data from a clienthttpresponse, but don ' t need to worry about EXCE ption handling or closing resources.
Simply put: Parse the HTTP response data without worrying about exceptions and resource shutdowns. The interface has three implementation classes:
Headersextractor Used to extract the request header.
Httpmessageconverterextractor Used to extract the response body.
Responseentityresponseextractor Use Httpmessageconverterextractor to extract the body (delegate mode), and then wrap the body and the response header, state into the Responseentity object.
6.4.2 Extract Response body extraction is divided into three steps:
(1) Extractor httpmessageconverterextractor Find available Converters initializes the converter collection in the default Resttemplate constructor, including:

Converter

conversions Type
bytearrayhttpmessageconverter byte[]
Stringhttpmessag Econverter String
resourcehttpmessageconverter Resource
sourcehttpmessageconverter javax.xml.transform.*
allencompassingformhttpmessageconverter multivaluemap
jaxb2rootelementhttpmessageconverter xmlrootelement,xmltype (annotations)
...  
mappingjackson2httpmessageconverter Json
In addition to the first five, other converters will be tried by ClassLoader to load a class to determine whether the project contains a package, and then decide whether to join the converter collection.
The extractor traverses the converter collection to find the available converters, where Mappingjackson2httpmessageconverter is always the last, because the class implements the Generichttpmessageconverter, which is a general purpose converter, It is only available if the appropriate converter is not found. Spring provides an implementation of this class to ensure that the class is always available.

(2) Converter to find available DeserializerThe converter holds a collection of deserializer caches, first looking from the cache
If a deserializer is already available, it is returned directly. Otherwise, a new deserialization is created. The deserializer holds information such as the domain, method, constructor, and so on, of the class to be deserialized, and when deserialized, creates a new instance using the constructor. In Jackson, for example, the process of creating a deserializer is interesting to look at in Jackson-databind-xxx.jar. The call stack is as follows (look up from the bottom): beandeserializerfactory.addbeanprops/addobjectidreader/addreferenceproperties/addinjectables
Beandeserializerfactory.buildbeandeserializer
Beandeserializerfactory.createbeandeserializer
(3) Deserialization of the Deserializer

TOKEN

One or a set of characters in a JSON
Start_object {
End_object }
Start_array [
End_array ]
Value_true True
Value_false False
...

Call stack:

Spring Resttemplate Detailed

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.