Apicloud's Cloud API Inquiry tour

Source: Internet
Author: User
Tags getmessage response code sha1 stringbuffer

What the Cloud API is. Why should we use.

First, let's take a look at a reader Web introduction to the Cloud API.
Apicloud's "Cloud API" plan was designed to allow developers to automatically generate the various cloud service interfaces needed for mobile applications by requiring little or no server-side coding. The Cloud API service includes data services, push, cloud repair, and large data analysis.

Apicloud's Data services support the automatic generation of RESTful APIs, which provide flexible data service support for the app in mobile scenarios. At the same time, a large number of applications of NoSQL provide sufficient support for large data of Apicloud. Apicloud's "Cloud API" provides access control model security based on ACLs (Access controller List) and RBAC (role Based access controls), allowing developers to balance mobile applications with business agility and security.
Apicloud's "Cloud API" has typical "cloud" features and "Big Data" features.

For app developers to provide cloud API services and data storage services, dynamic generation of RESTful API, support Online NoSQL datasheet design, API Debugging and consumption analysis, while providing push, cloud repair, large data analysis and other services, greatly simplifies the server-side development work.

In a word, we don't need to write back code, we can access the contents of the database directly through the system generated restful API, and many other functions are provided.

No more nonsense, the following is the beginning of the Apicloud Cloud API exploration.

1. Enter Apicloud official website, register an account.
2. Log into the development console and create a new application.

Enter application name and description, create.
3. Go to the big homepage of the application.

Here, we can see the appkey,appid of this application, as well as other logos. will be used later.
4. We are concerned about the cloud database, so click on the left column.

Click to open the cloud service.

Select a cloud storage provider. Seven Neu Yun is mainly the picture audio, we do not need, so we choose to shoot cloud service providers, OK.

We will find that this database is self-contained with 5 system tables: Accesstoken, file, role, rolemapping, user.
The underscore in front, just to differentiate this is the system table. And when it's really used, it's not underlined.
They all have what concrete function, for the moment we do not care, later do the introduction.

Here you can create your own class, where the class corresponds to the table of the SQL database. Create a class that you can then understand to create a table. We try to create an information class–message.

Click Create

We'll find that this class has 3 fields by default. The difference is id,createdat,updateat, what is the meaning, self-evident.
We create a string-type content field for the message.

Other delete, rename and other operations, can be found on the above. We can try it on our own.

We would like to try to manipulate the database additions and deletions to check.
OK, click on the left side of the API debugging.

Here you can perform an API online test to check the table for additional deletions.

1. Try adding a piece of data to the message first.
Class Select the Message table, method to select Create a new instance.
Enter at the body:
{"Content": "contents of the first message"}

Click Send Request

We can see the request URL path, the response response body, and the response code, the response header.

You can also see the AJAX code implementations for this addition operation.

OK, let's go back to the database and see what's changed.

Indeed, the message contained a data that was successfully tested.

API online Testing, there are many, here is not one to try.

The API online test was successful, so how do we implement this in android? The official website does not give a Java implementation example. So it doesn't matter, we can do it by imitating the AJAX Web request.

In our project, we have a good understanding of the application of okhttp. Then, we use okhttp to realize.
Before writing the code, you first need to make a simple introduction to the RESTful style API.
The Restful API allows you to interact with API Cloud with any device that can send HTTP requests.
Here take the official website example to see.

The method of HTTP request post,delete,put,get respectively corresponding to the increase of the deletion check.
It's easy for us to find the law.
For example, the first line, the post is created, the path is/mcm/api/,
That means adding a piece of data to the classname.

Here do not do in-depth parsing, interested, come here to see:
Http://www.ruanyifeng.com/blog/2014/05/restful_api.html

Now start the code test:

Before that, I have added a series of custom fields to the system table user, Nickname,realname, etc.

Okhttputils.post (). URL ("Https://d.apicloud.com/mcm/api/user"). AddHeader ("Content-type", "Application/js On;charset=utf-8 "). AddHeader (" X-apicloud-appid ", Constant.appid). AddHeader (" X-apicloud-appkey ", Constant . Getappkey ()). Addparams ("username", "QQ"). Addparams ("Password", "123456"). Addparams ("email", "2 70949894@qq.com "). Addparams (" nickname "," Wym "). Addparams (" StudentID "," 201324133121 "). Addparams ("Realname", "Wu Yiji"). Addparams ("Sex", "0"). Addparams ("mobile", "15622625081"). Build (). E
                Xecute (New Stringcallback () {@Override public void OnError (call call, Exception e, int id) {
            Toast.maketext (Mainactivity.this, E.getmessage (), Toast.length_short). Show (); @Override public void Onresponse (String response, int id) {Toast.maketext (Main Activity.this, response, Toast.length_short). Show (); }
        });

Run the first time, create a user,

Run the second time, the user already exists,

To the database to see, there is already a number of data.

Here's how to analyze the code:

. AddHeader ("Content-type", "Application/json;charset=utf-8")
. AddHeader ("X-apicloud-appid", Constant.APPID)
. AddHeader ("X-apicloud-appkey", Constant.getappkey ())

For post and put requests, the body of the request must be in JSON format, and the Content-type of the HTTP header needs to be set to Application/json.
User authentication is done through the HTTP header.
The X-apicloud-appid header indicates which app program is running.
The X-apicloud-appkey head is used to authorize authentication terminals.
So how do AppID and Appkey get, we see:

public class Constant {public
    static String APPID = "A6929067641945";
    public static String Appkey = "ac9ae246-4f70-d990-96e7-183e2d9ea001";
    public static String Getappkey () {
        Long now = new Date (). GetTime ();
        Return DECRIPT.SHA1 (constant.appid + "UZ" + Constant.appkey + "UZ" + Now) + "." + Now;
    }
}

AppID can be obtained from the Application control management page.
Appkey, there's a formula for this:

Appkey = SHA1 (Application ID + ' UZ ' + Apply key + ' UZ ' + current time milliseconds) + '. ' + Current time milliseconds
Where SHA1 is a cryptographic method.

. Addparams ("username", "QQ")
. Addparams ("Password", "123456")

Self - evident.

Here is the SHA1 algorithm, you can download it yourself:

public static string SHA1 (String decript) {
    try {
        MessageDigest digest = Java.security.MessageDigest
                . getinstance ("SHA-1");
        Digest.update (Decript.getbytes ());
        byte messagedigest[] = Digest.digest ();
        Create Hex String
        stringbuffer hexstring = new StringBuffer ();
        The byte array is converted to a hexadecimal number for
        (int i = 0; i < messagedigest.length; i++) {
            String Shahex = integer.tohexstring (messaged Igest[i] & 0xFF);
            if (Shahex.length () < 2) {
                hexstring.append (0);
            }
            Hexstring.append (Shahex);
        }
        return hexstring.tostring ();

    } catch (NoSuchAlgorithmException e) {
        e.printstacktrace ();
    }
    Return "";
}

Okay, then go on:
The server database has user information and we try to get the user information.
We can use this URL to access the user of the specified ID.
Https://d.apicloud.com/mcm/api/user/[id]

As you can see in the database, id = 57e7905be26c90a0079722ea

We'll get the data for it:

String url = "https://d.apicloud.com/mcm/api/user/" + "57e7905be26c90a0079722ea";
Okhttputils.get ()
        . URL (url).
        addheader ("Content-type", "Application/json;charset=utf-8").
        AddHeader ("X-apicloud-appid", Constant.appid)
        . AddHeader ("X-apicloud-appkey", Constant.getappkey ())
        . Build ()
        . Execute (New Stringcallback () {
            @ Override public
            void OnError (call call, Exception e, int id) {
                toast.maketext (mainactivity.this, E.getmessage () , Toast.length_short). Show ();

            @Override public
            void Onresponse (String response, int id) {
                toast.maketext (mainactivity.this, Response, Toast.length_short). Show ();
            }
        };

Return 401,401 represents no permissions.
Let's go backstage and modify the permissions.

Set the Get permission to the permissions that all users have

To run again, you can get the data.

We use the knee to think about it, it is estimated that there is no login, can not get permissions.

OK, first set the permissions back to only log on to have permissions.
Next, do the login operation:
Access URL
Https://d.apicloud.com/mcm/api/user/login

Okhttputils.post ()
        . URL ("Https://d.apicloud.com/mcm/api/user/login")
        . AddHeader ("Content-type", " Application/json;charset=utf-8 ")
        . AddHeader (" X-apicloud-appid ", Constant.appid)
        . AddHeader (" X-apicloud-appkey ", Constant.getappkey ())
        . Addparams (" username "," QQ "
        . Addparams (" Password "," 123456 ")
        . Build ()
        . Execute (New Stringcallback () {
            @Override public
            void OnError (call call, Exception e, int id) {
                Toast.maketext (mainactivity.this, E.getmessage (), Toast.length_short). Show ();

            @Override public
            void Onresponse (String response, int id) {
                toast.maketext (mainactivity.this, Response, Toast.length_short). Show ();

            }
        };

Run Result:

From the return result, you can see an ID, which is estimated to be a class-token thing. We
Think on your knees and estimate that this ID is the key that proves you have logged in. Let's take a look at the database:

Here's a accesstokens (the data type is relation, explained later), he can be clicked, we click in.

Left _user a _accesstoken is listed below, with a piece of data that reads:
lmmuarlbfe0k18xiakptozlbigturnekubtwraxc0tfdxs9xfhnqppsj3sxn3w7d

He happens to be the ID that the user returns when he logs in.

OK, we have the key, then we access the user table to get the data. According to the above example:
Add this sentence:
. AddHeader ("Authorization", "lmmuarlbfe0k18xiakptozlbigturnekubtwraxc0tfdxs9xfhnqppsj3sxn3w7d")

Okhttputils.get ()
        . URL (url).
        addheader ("Content-type", "Application/json;charset=utf-8").
        AddHeader ("X-apicloud-appid", Constant.appid)
        . AddHeader ("X-apicloud-appkey", Constant.getappkey ())
        . AddHeader ("Authorization", " Lmmuarlbfe0k18xiakptozlbigturnekubtwraxc0tfdxs9xfhnqppsj3sxn3w7d ")//There is more to this sentence
        . Build ()
        . Execute (NEW Stringcallback () {
            @Override public
            void OnError (call call, Exception e, int id) {
                toast.maketext ( Mainactivity.this, E.getmessage (), Toast.length_short). Show ();

            @Override public
            void Onresponse (String response, int id) {
                toast.maketext (mainactivity.this, Response, Toast.length_short). Show ();
            }
        };

This allows the user's data to be accessed normally.

So what is Accesstoken?
As we can see, _accesstoken is a system table. Click to open the view:

As we can guess, this table is where the token of the login is stored.
Every time you log in, the IDs you return are different, so there's definitely a new data store for each time.
Let's make a few more requests to log in:

Refresh, the _accesstoken indeed a few more data.

Next, continue to do the test.
The following measure is to update a user's data.
Https://d.apicloud.com/mcm/api/user/[id]

Okhttputils.post ()
        . URL ("https://d.apicloud.com/mcm/api/user/" + "57e7905be26c90a0079722ea")
        . AddHeader ( "Content-type", "Application/json;charset=utf-8")
        . AddHeader ("X-apicloud-appid", Constant.appid)
        . AddHeader ("X-apicloud-appkey", Constant.getappkey ())
        . AddHeader ("Authorization", " Lmmuarlbfe0k18xiakptozlbigturnekubtwraxc0tfdxs9xfhnqppsj3sxn3w7d ")
        . Addparams (" _method "," put ")
        . Addparams ("nickname", "Update Name")
        . Build ()
        . Execute (New Stringcallback () {
            @Override public
            Void OnError (call call, Exception e, int id) {
                toast.maketext (mainactivity.this, E.getmessage (), Toast.length_short). Show ();
            }

            @Override public
            void Onresponse (String response, int id) {
                toast.maketext (mainactivity.this, Response, Toast.length_short). Show ();
            }
        };

The update was successful.

In fact, all the methods can be submitted by post, and then through this method to set the method.
. Addparams ("_method", "put")

The following test batch operations:

To reduce the time wasted by too many network interactions, you can create/update/delete multiple objects in a single request.
Each operation in a batch has a corresponding method, path, and body, which can replace the HTTP method that you would normally use. These operations are performed in the order in which they were sent.
The implementation of the official Ajax is this:

$.ajax ({
      "url": "Https://d.apicloud.com/mcm/api/batch", "
      type": "POST",
      "cache": false,
      "headers" : {
        "x-apicloud-appid": "{{your_app_id}}",
        "X-apicloud-appkey": "{{encrypted key}}"
      },
      "data": {
        " Requests ": [{
            " method]: "POST",
            "path": "/mcm/api/company",
            "body": {
                "name": "Apicloud",
                " Address ":" Beijing ... "
            }
        ,
        {
            " method ":" POST ",
            " path ":"/mcm/api/company ",
            " body ": {
                "Name": "Baidu",
                "address": "Beijing West Two Flags"}}}
). Done (function (data, status, header) {
      // Success Body
}). Fail (function (header, status, Errorthrown) {
      //fail body
})

However, using okhttp does not seem to simulate the passing of this parameter. If you have a way, please let me know.
The official provided a package of HttpClient package JAVA-SDK to operate these additions and deletions. Can download here:
Https://github.com/APICloud-com/Java-sdk
There are also tutorials in use.

Let's do a batch operation that generates two user objects.

Resource Resource = new Resource (constant.appid, constant.appkey, null);
        If the operation requires permissions, set permissions here and set token
        //resource.setauthorization (" Lmmuarlbfe0k18xiakptozlbigturnekubtwraxc0tfdxs9xfhnqppsj3sxn3w7d ");
        Jsonobject params = new Jsonobject ();
        Jsonarray array = new Jsonarray ();
        Jsonobject json = new Jsonobject ();
        Json.put ("Method", "POST");
        Json.put ("Path", "/mcm/api/user");
        Jsonobject BODY = new Jsonobject ();
        Body.put ("username", "user1");
        Body.put ("Password", "123456");
        Json.put ("Body", the body);
        Array.add (JSON);

        Jsonobject json1 = new Jsonobject ();
        Json1.put ("Method", "POST");
        Json1.put ("Path", "/

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.