Light, anyone will write the service solution-rest and JSON

Source: Internet
Author: User
Tags object serialization
1. Rest1.1 Origin

N years ago, when talking about cross-platform service solutions, the Bulls Thought of "socket server" and the soldiers kept moving back to the corner of the meeting room.
A few years ago, when talking about cross-platform service solutions, even customers would think of "Web service ".
Now, you can write the client and server of a service in a few minutes using the REST style.

1.2 first sight

Rest is a word first, and then represents a service provision mode. Well, shengxian said that any service protocol can be split into transmission protocol, service mode, and three-dimensional data format expression. Rest relies on HTTP as the transmission mechanism, and the request-reponse mode, data is any pre-negotiated format.

As a result, clients in any language access a URL using an HTTP library, and write the request information as XML, JSON, or pure string in the post object. The server can implement a servlet or even JSP/asp/PHP at will, receive requests from the client, and return the XML/JSON/string results.

So easy, do you think of the implementation method immediately. In Java, the httpclient client of Apache is used to send a POST request.

HttpClient httpClient = new HttpClient();EntityEnclosingMethod method = new PostMethod(url); method.setRequestBody(fooXml);method.setRequestHeader("Content-type","application/xml; charset=utf8"); httpClient.executeMethod(method); String body = method.getResponseBodyAsString(); 

Another XML/JSON operation library is highly recommended for codehaus xstream pipeline, which is beautifully converted between XML/JSON and Java objects. It is much more convenient than other heavy-duty XML binding solutions. below is the code for conversion between XML and Java objects.

Xstream  xs = new Xstream(); String xml = xs.toXML(foo);Foo foo = (Foo)xs.FromXML(xml);  

. NET is simpler. Both HTTP and XML libraries are provided.
This is the most attractive part. In rest, writing services is no longer a framework-level task, and configuration files and callback functions are no longer required. You only need to know a few APIs or even APIs, hand DIY service. Infoq's article is good: simple Java and. Net SOA interoperability compliance

1.3 principles

Luo Yun said that rest is a simple interaction oriented to messages (resources) and gradually replaces RPC. Real rest has the following ideas:

  • Define an internet ID for all "things" and connect them. A good idea.

    <order self='http://example.com/customers/1234' ><amount>23</amount><product ref='http://example.com/products/4554' /></order>

  • The first three Methods defining standard put/get/delete/post methods have idempotence, so that no specific API is required between Internet applications.
    For services such as "approval", there is a lack of direct expression ability. Only one resource can be used for approval. The post representative initiates approval and the delete representative revokes the service. Although it is awkward, it always passes the approval process.
  • Multiple Expressions of resources.
    The client initiates a request such as application/vnd. mycompany. Customer + XML and accept: text/X-vCard. The server then renders the same resource into different responses.
  • Stateless communication.
    Status is either put into the resource status or saved on the client. In this way, the customer does not rely on the server instance, and the server can be expanded or restarted at will.
  • The natural use of HTTP compression and caching mechanisms
    HTTP compression mechanism, as long as the client says it accept encoding: gzip, the server can compress and transmit data.
    Use etags to reduce web application bandwidth and load (infoq) failover)

The etag principle is very simple, that is, the server can include an etag in response. The next time the user's header can include an IF-None-match: etag's value, the server determines etag, if no modification is made, HTTP/1.x 304 not modified is returned.
Two algorithms have different effects.

    1. The simple algorithm uses the hashcode returned from the page as the etag. The server calculates the final page and performs hash comparison. If it is the same as the etag of the customer, no 304 is returned, this algorithm is simple and mainly saves data transmission time.
    2. The complex algorithm sets the version number for the page and uses the version number as etag. Set the page affected by resource changes on the server. For example, use the listener of Hibernate to add, delete, and modify any versions that may be affected. This algorithm is relatively complex, but it also saves the server computing time and transmission time.
Cost 1.4

Of course, simple rest also has a simple price, such as lack of mechanisms such as transactions, reliability, WS-address, and UDDI. However, these mechanisms are rarely used in the Orthodox WebService world. For pure WebServices that do not use any additional mechanisms, you can consider using rest writing, or designing your own protocol like DIY transaction handler.

In addition, the customer needs to self-interpret payload, or rely on the SDK provided by the server side, instead of generating DTO from the direct WSDL, wadl scheme is not final yet.

Finally, rest can be used as a service solution as well as a web application MVC solution. For example, cetia4 (https://cetia4.dev.java.net/#) is called to replace the traditional MVC framework. However, I think after a bunch of frameworks, the simplicity gradually loses its meaning. In addition, since Web applications have not been used recently, it takes half a day to read its tutorial documents and stop paying attention to them.

2. JSON

JSON introduction (dev2dev) plugin ). If there is a large amount of data transmitted,JSON (JavaScript Object Notation)To simplify the complex XML in XML, especially soap. For example:

   {"product":{"name":"Banana","id":"123","price":"23.0"}}

Each language has n JSON interpreters. Xstream also uses jettison connector as the driver to support Java object serialization and JSON serialization. When an xstream object is created, change the parameter to jettision. Other operations are the same as those in XML. For details, see JSON tutorial connector.

    XStream xstream = new XStream(new JettisonMappedXmlDriver());

Coincidentally, Apache cxf (xfire) also uses Jettison to Support Web Services in JSON format. For details, see its JSON support documentation.

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.