Basic knowledge about Android 10: WebService 02: Rest

Source: Internet
Author: User

This document describes how to use WebService on the android client. The first is about ksoap2 and the second is about rest.

Basic knowledge about Android 10: WebService 01: ksoap2

Basic knowledge about Android 10: WebService 02: Rest

1. Rest instances

Recently, the Project released WebService implementation in the rest mode of Apache cxf. The development of Android mobile background services is as follows.

Mobile Platforms developed using Android + rest WebService in the project seldom use the SOAP protocol. The main SOAP Protocol Resolution problems increase the amount of code. The advantage of using restfull to develop WebService is relatively simple compared with the WebService of the soap protocol. At the same time, it simplifies the mobile phone resolution work, reduces the pressure on the mobile phone end, and improves the mobile phone response efficiency.

Mobile Background Service:

package com.easyway.rest.ws;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
/ **
 * The server releases a simple WebService service
 * Receive the information sent by the server on the mobile phone.
 * Use the Apache HttpClient library to access JAX-RS web services. Jersey is JAX-RS
 * Reference implementation, which simplifies the development of RESTful Web services in a Java ™ environment. Android
 * Is a popular smartphone, this article will show how to create a JAX-RS client for Android.
 * You will create an Apache HttpClient library client to access JAX-RS Web services.
 * JAX-RS required jars:
 * jersey-bundle-1.8.jar, jersey-server-1.10.jar, jsr311-api-1.1.1.jar
 * asm-3.1.jar
 * Use a root resource class to create a RESTful Web service resource. The root resource class is with @PATH
 * Annotated POJO. It contains at least one annotated method, the annotation is @PATH, @GET, @PUT, @POST
 * Or @DELETE.
 *
 * On the server, as specified by web.xml, the init parameter com.sun.jersey.config.property.resourceConfigClass
 * Start as com.sun.jersey.api.core.PackagesResourceConfig, and the init parameter
 * com.sun.jersey.config.property.packages starts as com.easyway.rest.ws.
 * Find the root resource class com.easyway.rest.ws.HelloWorldResource.
 *
 * Remarks: If the JAXRS service is released using Jersey, you need to configure:
 * <pre>
 * <servlet>
* <description> JAX-RS </ description>
* <servlet-name> JAX-RS-Servlet </ servlet-name>
* <servlet-class> com.sun.jersey.spi.container.servlet.ServletContainer </ servlet-class>
* <init-param>
* <param-name> com.sun.jersey.config.property.resourceConfigClass </ param-name>
* <param-value> com.sun.jersey.api.core.PackagesResourceConfig </ param-value>
* </ init-param>
* <init-param>
* <param-name> com.sun.jersey.config.property.packages </ param-name>
* <param-value> com.easyway.rest.ws </ param-value>
* </ init-param>
* <load-on-startup> 1 </ load-on-startup>
* </ servlet>
* <servlet-mapping>
* <servlet-name> JAX-RS-Servlet </ servlet-name>
* <url-pattern> / services / * </ url-pattern>
* </ servlet-mapping>
 *
 * </ pre>
 *
 * @author longgangbai
 *
 * /
@Path ("/ helloworld")
public class HelloWorldResource {
/ **
* A simple text message
* @return
* /
     @GET
     @Produces (MediaType.TEXT_PLAIN)
     public String getClichedMessage () {
     return "Hello Android";
     }
}
 
The web.xml configuration is as follows:

<? xml version = "1.0" encoding = "UTF-8"?>
<web-app xmlns: xsi = "http://www.w3.org/2001/XMLSchema-instance" xmlns = "http://java.sun.com/xml/ns/javaee" xmlns: web = "http : //java.sun.com/xml/ns/javaee/web-app_2_5.xsd "xsi: schemaLocation =" http://java.sun.com/xml/ns/javaee http://java.sun.com /xml/ns/javaee/web-app_2_5.xsd "id =" WebApp_ID "version =" 2.5 ">
  <display-name> JAXRSWebService </ display-name>
<servlet>
    <description> JAX-RS </ description>
    <servlet-name> JAX-RS-Servlet </ servlet-name>
    <servlet-class> com.sun.jersey.spi.container.servlet.ServletContainer </ servlet-class>
    <init-param>
        <param-name> com.sun.jersey.config.property.resourceConfigClass </ param-name>
        <param-value> com.sun.jersey.api.core.PackagesResourceConfig </ param-value>
    </ init-param>
    <init-param>
        <param-name> com.sun.jersey.config.property.packages </ param-name>
        <param-value> com.easyway.rest.ws </ param-value>
    </ init-param>
    <load-on-startup> 1 </ load-on-startup>
  </ servlet>
  <servlet-mapping>
    <servlet-name> JAX-RS-Servlet </ servlet-name>
    <url-pattern> / services / * </ url-pattern>
  </ servlet-mapping>
</ web-app>
 
Mobile phone front desk service:

package com.easyway.rest.ws;

import java.io.IOException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import android.app.Activity;
import android.os.Bundle;
import android.os.StrictMode;
import android.widget.TextView;
/ **
 * Android platform mainly provides four data storage methods: Shared Preferences, file storage, Sqlite storage and network storage. among them:
      1) Shared Preferences A lightweight key-value storage mechanism, specifically used to store key-value pair data, and can only store basic data types
                        (Boolean, int, long, float, and String); it is usually used to store application configuration information.
      2) File storage Operate files through FileInputStream and FileOutputStream. In Android, files are private to an application.
       An application cannot read or write files of other applications.
      3) SQLite storage SQLite is a lightweight database that supports standard SQL. Its design goal is embedded, and the occupied resources are very low. In embedded devices,
          Only a few hundred K of memory is enough. The Android platform also provides us with a SQLite database.
      4) Network storage The above three methods of data are stored on the mobile phone, and the data stored on the network is stored on a remote server, and the mobile phone client connects to the network to store and obtain data.

      HttpClient to be explained today is just one of the commonly used network storage tools. I remember the first contact with HttpClient was two years ago, when I was going to be a vertical search engine,
      The data naturally comes from the Internet. Through a crawler system, it continuously crawls the data of interest from the designated website, and then realizes massive data through the Lucene search engine framework.
      Quick search. The crawler system was originally intended to be implemented using the open source crawler framework Heritrix, but after a period of contact, it was found that Heritrix was too large and
      Running for an independent system, which is inconvenient to embed in the existing system, coupled with the high learning cost, finally chose "HttpClient + HtmlParser" to achieve
      Small crawler system; HttpClient can simulate HTTP POST and GET requests, used to obtain web page data from a specified website, and HtmlParser is used to parse crawl to
      Page, filter HTML tags to get the final data.
      Did you find that HttpClient is quite powerful? Let's see what it comes from. "HttpClient is a sub-project under Apache Jakarta Common and can be used
      Provide efficient, latest, and feature-rich client programming toolkit that supports the HTTP protocol, and it supports the latest version and recommendations of the HTTP protocol. "If you have not previously
      Have contacted HttpClient, then you only need to remember two points:
          1) HttpClient is an HTTP protocol development package;
          2) HttpClient is not a patent of Android.

      Function introduction of HttpClient:
            1) Implemented all methods of HTTP request (such as GET, POST, PUT, HEAD, etc.);
            2) Support automatic steering;
            3) Support HTTPS protocol;
            4) Support proxy server, etc.
      HttpClient Basic Use (Take POST request as an example):
            1) Create an HttpClient instance (similar to a browser client);
                        HttpClient client = new DefaultHttpClient ();
            2) To create an HttpPost request, you need to pass the requested URL to the HttpPost construction method;
                        HttpPost post = new HttpPost (requestUrl);
            3) Issue a POST request (call the execute () method of HttpClient, and the parameters of execute () are HttpPost instances);
                        HttpResponse response = client.execute (post);
            4) Read the return result;
            5) Release the connection;
            6) Process the returned results.

      To use HttpClient on the Android platform, there is no need to add additional jar packages, because the Android platform absorbs many excellent open source frameworks, including HttpClient,
      Let's look at an example of using HttpClient on the Android platform.
Note: Did you find HttpClient easy to use? In fact, the above explained is only the most basic function of HttpClient (initiating POST request); we are in the browser client
Most operations performed by HttpClient can be simulated, such as: submitting forms, querying data, uploading and downloading documents, page jumps, session storage, etc. For example, everyone
Often playing "snatching parking spaces" and "stealing vegetables" can be achieved automatically through HttpClient programming.


 *
 *
 * The client calls JAXRS WebService service through Apache HttpClient.
 * Develop Apache HttpClient client for Android to access JAX-RS Web service.
 *
 * Remark: localhost or 127.0.0.1 cannot be used when accessing JAXRS Web service
 * Because the android simulation opportunity calls its own Linux kernel operating system, it may not find related services.
 * It is best to fill in the ip address as follows:
 * "http://192.168.134.1:8080/JAXRSWebService/services/helloworld";
 *
 * @author longgangbai
 *
 * /
public class AndroidJAXRSWebServiceActivity extends Activity {
    private static final String processURL = "http://192.168.134.1:8080/JAXRSWebService/services/helloworld";
private TextView txResult;
The
    / **
     * Called when the activity is first created.
     * /
    @Override
    public void onCreate (Bundle savedInstanceState) {
    /// The following code must be added after Android2.2
//Android4.0 used in this application
// Set the thread strategy
StrictMode.setThreadPolicy (new StrictMode.ThreadPolicy.Builder ()
         .detectDiskReads ()
         .detectDiskWrites ()
         .detectNetwork () // or .detectAll () for all detectable problems
         .penaltyLog ()
         .build ());
// Set the strategy of the virtual machine
StrictMode.setVmPolicy (new StrictMode.VmPolicy.Builder ()
.detectLeakedSqlLiteObjects ()
//. detectLeakedClosableObjects ()
.penaltyLog ()
.penaltyDeath ()
.build ());

        super.onCreate (savedInstanceState);
        // Set the UI layout
        setContentView (R.layout.main);
        // Get the result display text box
        txResult = (TextView) findViewById (R.id.tvresult);
        // Get the result information of JAXRS WebService
        getJAXRSWebService ();
    }
    
    / **
     * Get the result information of JAXRS WebService
     * /
    public void getJAXRSWebService () {
    try {
    // Create an HttpClient object
    HttpClient httpclient = new DefaultHttpClient ();
        // Create HttpGet object
    HttpGet request = new HttpGet (processURL);
    // Request information type MIME output for each response type (plain text, html and XML). The allowed response type should match the MIME type generated in the resource class
    // The MIME type generated by the resource class should match an acceptable MIME type. If the generated MIME type does not match the acceptable MIME type, then the
    // Generate com.sun.jersey.api.client.UniformInterfaceException. For example, set the acceptable MIME type to text / xml, and set
    // The generated MIME type is set to application / xml. UniformInterfaceException will be generated.
    request.addHeader ("Accept", "text / plain");
        // Get the result of the response
HttpResponse response = httpclient.execute (request);
// Get HttpEntity
HttpEntity entity = response.getEntity ();
// Get the result information of the response
String result = EntityUtils.toString (entity);
txResult.setText (result);
    } catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace ();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace ();
}
    }
}

2. Rest Theory

In the basic technical implementation of SOA, WebService occupies a very important position. We usually mention the first idea of WebService is that soap messages interact on various transmission protocols. In recent years, the idea of rest has gradually been accepted by everyone along with SOA. At the same time, the open APIs provided to developers by major websites have aroused the upsurge of rest-style WebService.
Before receiving an email for a new requirement, I only read Fielding's restful doctoral thesis through a thorough understanding of rest. To be honest, I wanted to understand such a new concept, I just had a superficial understanding of its internal thoughts.
The latest requirement of ASF is that it may need to implement rest-style WebService integration, so we have to take a good look at the true meaning of rest and the current design methods of major websites. Later I want to express some of my views and opinions of this beginner. I hope to get more feedback and opinions before I integrate rest into ASF.
2.1 http: // service.ap-southeast-1.maxcompute.aliyun-inc.com
What is soap? I don't want to mention it. Google is full of eyes. In fact, soap was originally a solution for rpc. Simple Object Access Protocol is very lightweight. At the same time, it can be used as an application protocol to transmit messages (HTTP, SMTP, etc.) based on multiple transmission protocols ). However, with the wide application of soap as a WebService and the increasing addition of content, developers now think that soap is very heavy and has a high threshold for use. In the subsequent development of soap, the establishment of a series of WS-* protocols increased the maturity of soap and increased the burden on soap.
2.2 rest
In fact, rest is not a protocol or a standard, but an interpretation of the original design of the HTTP protocol. Nowadays, HTTP is widely used as a transmission protocol, rather than the application protocol that the original designer considered. A soap-type WebService is the best example. a soap message simply carries an HTTP protocol as a message, so that all parameters (such as encoding and error codes) in the HTTP protocol are ignored. In fact, the most lightweight application protocol is the HTTP protocol. The abstract get, post, put, and delete in the HTTP protocol is like the most basic addition, deletion, modification, and query in the database, the various resources on the Internet are like records in databases (which may not be a good analogy). Operations on various resources can always be abstracted into these four basic operations, after defining the resource locating rules, resource operations can be implemented through the standard HTTP protocol, and developers will also benefit from this lightweight protocol.
As you can understand, there are several key points in the concept of rest:
1. Resource-Oriented Interface Design
All interface designs are designed for resources, which is similar to our object-oriented and process-oriented designs. However, the operating entities on the network are regarded as resources, at the same time, the URI design also reflects the resource positioning design. There will be some web site API design said that rest design, in fact, is a mixture of RPC-REST, not the idea of rest.
2. Crud based on abstract operations
This is very simple. The get, put, post, and delete operations in HTTP correspond to four types of operations: read, update, create, and delete. If they are only operations on resources, it is enough to abstract these four types. However, for some complex business service interface designs, such abstraction may not be able to meet the requirements. In fact, this problem is also exposed in the API design of the following websites. If you want to design completely according to the rest idea, then the applicable environment will be limited, it is not universally applicable.
3. HTTP is the application protocol rather than the transmission protocol.
This is clearly reflected in the API analysis of major websites. In fact, some websites are already on the way to soap, which is the concept design of rest, it is actually a set of private soap protocols, so it is called a rest-style custom SOAP protocol.
4. Stateless, self-contained
This is not only for rest, but also for interface design. It is also the most basic guarantee for scalability and efficiency, even for WebService using soap.
2.3 rest vs soap
Maturity:

Although soap has evolved from its original intention to the present, the release and calling of services in heterogeneous environments, as well as vendor support have all reached a relatively mature level. Web services that interact with each other through soap on different platforms can communicate well (in some complex and special parameters and response object parsing, the Protocol is not detailed, as a result, some corrections are required)
Rest many foreign websites have released their own development APIs, many of which provide soap and rest Web Services. According to the survey, the rest style usage of some websites is higher than that of soap. However, since rest is just an idea of implementing Resource Operations Based on HTTP protocol, there is a set of rest implementations for each website. The rest API style of each major website will be discussed later. It is precisely because of their respective implementations that the performance and availability will be much higher than the Web Service released by soap, but the unified and universal aspect is far inferior to soap. Because the SP of these large websites often focus on the API development of this website, the general requirements are not high.
For the release of rest-style Web Services on ASF, you can refer to the design of several major websites (the solution of brothers is to refer to the design mode similar to that of Flickr ), however, since there is no authoritative protocol similar to soap as a specification, various rest-implemented protocols can only be regarded as private protocols. Of course, they must follow the rest idea, but there are too many constraints in such details. The future development of rest will also directly affect whether the design can have good vitality.
In general, soap is better than rest in terms of maturity.
Efficiency and ease of use:
The SOAP protocol defines message bodies and headers, And the scalability of message headers provides the basis for extension of various Internet standards. The WS-* series are relatively successful specifications. However, due to the constant expansion of the content of SOAP Protocol due to various requirements, the performance of soap processing has declined. At the same time, it also increases in usability and learning costs.
Rest has been paid attention to by people. In fact, it is also very important because of its efficiency and simplicity and ease-of-use features. This efficiency stems from its resource-oriented interface design and operation abstraction, which simplifies developers' poor design and maximizes the use of HTTP's original application protocol design philosophy. At the same time, in my opinion, another attractive developer in rest is that it can well integrate many front-end technologies of current Web2.0 to improve development efficiency. For example, many rest APIs open to large websites have multiple return forms, except for the traditional XML as data bearer and JSON, RSS, atom, and other forms, this is a good way for many front-end website developers to prepare various resource information for mashups.
Therefore, rest is superior in terms of efficiency and ease of use.
Security:
This can be put into maturity. However, in the current Internet application and platform development and design process, security has been raised to a very high level, especially as an external interface for third-party calls, security may be higher than the business logic itself.
In terms of security, soap uses XML-security and XML-signature to form WS-Security to implement security control. Currently, it has been supported by various vendors ,. net, PHP, and Java are already well supported (although some details are still incompatible, it is basically possible to connect ).
Rest does not have any specifications to describe security. At the same time, websites that open rest APIs are mainly divided into two types, one is custom security information encapsulated in messages (which is no different from soap), and the other is guaranteed by hardware SSL, however, this only ensures point-to-point security. SSL is powerless if multi-point transmission is required. Security is also a big problem. At the BEA summit this year, we saw a demonstration of the use of saml2 for inter-site SSO. In fact, XML-security and XML-signature were directly used, efficiency does not seem very high. In the future, it is unknown whether the two standards will be used in the rest normalization and generalization processes. However, the more you add, the more advantages that rest will lose its efficiency.
2.4 application design and Transformation:
Our system either has services that need to be released, or services that have just been designed, however, it takes a little time for developers to accept the rest form with their traditional design ideas. At the same time, it is easier to design resource-based data service interfaces according to the rest concept. For some complex service interfaces, it may be far-fetched to design according to the REST style. In fact, you can see the interfaces of various websites. Many websites also need to input the function name as the parameter, which obviously violates the rest design idea.
Soap is designed for RPC, which is very easy for developers to accept. Therefore, there is no adaptation process.
In general, it is still an old concept, and the best fit is the best
There is no good or bad technology, but it is not suitable. If a good technology or idea is misused, it will be reversed. Both rest and soap have their own advantages. At the same time, if you transform rest in some scenarios, it will actually go to soap (such as security ).
Rest is suitable for Resource-based service interfaces and especially suitable for scenarios with high efficiency requirements but low security requirements. The maturity of soap can be provided to multiple development languages, facilitating interface design with high security requirements. Therefore, I think it makes no sense to say that the design model will be dominant. The key is to look at the application scenario.
At the same time, it is very important not to distort the rest. Many websites are now following the trend in developing restful interfaces. They are actually learning the rest interface. I don't know what it is, and the performance is not good, security is not guaranteed, and there is a seemingly similar leather bag.


References:

Android + rest WebService mobile development

Soapvsrest_webservice


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.