Android App development: Network Tools--volley (i)

Source: Internet
Author: User
Tags cloudant

Introduction


The network has been my personal blind spot, a while ago time to learn the use of volley network tools, but also through the source code for further learning, there are some ideas to share. In Android development, a lot of mature network tools, Android comes with HttpClient. There are also okhttp, the ion Open source project created by Koush and then the volley that Google later added to the source code of the Android project.

Why use volley, is because the volley use simple, logic clear, even in the debugging process, there is a problem. can also be located at high speed through the source code.


Volley compiling


Because you are accustomed to using the Gradle framework application. So I was trying to find out if I wanted to use volley for the first time, and I tried to get the library dependencies through the Gradle configuration file. Unfortunately, there is no. But even so volley libraries are very easy to make to add to our project.


First you need the ant compiler tool, and then assume that there is an Android system source code, volley in the Frameworks/volley folder.

Assuming that there is no Android source code, it is also very good to be able to clone the volley source code from the Android storage separately:

git clone Https://android.googlesource.com/platform/frameworks/volley
Unfortunately, the volley library's source code Android is not hosted on its GitHub account, so just can clone on the Googlesource, of course, in the domestic also need to first FQ talent enough.

For volley source code structure:


After cloning succeeds. It is easy to compile with Ant and, of course, it can be compiled directly from make under the full Android source code, but the time must be much longer. Here's an example of using Ant compilation to run:

Ant Jar
As a result, you see:


This allows the jar package to be built, very handy, and then added to project to be able to use it.

Volley use


The volley network request parent class is request<t>. Can be provided to developers for inheritance. Several types of requests that are frequently used in development are also preset at the same time. Below are two: Stringrequest and Jsonobjectrequest.

In order to be closer to the actual use, the following will use volley and cloudant communication to do a demonstration sample.

Cloudant is a company that provides cloud services business. It provides developers with free cloud storage, cloud database services. The process of its registration is not described in this article, very easy.

Start directly from the login:


1. Request a queue for network requests

A very big feature of the volley. Is that all network requests do not need to be run by the developers themselves, but are thrown into the volley request queue after the request is constructed, and the queue is requested in turn, which saves a lot of trouble. Developers don't have to worry about whether network requests will conflict. Whether it will be in the main thread, these annoying things volley network queue to help us conquer.

In general, an application assumes that the network request is not particularly frequent and can only have a request queue (corresponding application), assuming many or other circumstances, it can be an activity corresponding to a network request queue, detailed analysis.

The code below shows how to request a volley network request queue:

Requestqueue mqueue;mqueue = Volley.newrequestqueue (Getapplicationcontext ());

This successfully applies for a network request queue, assuming that there is only one, you can apply in the application.


2. Login with Volley Cloudant

If you have successfully registered. Logon name Foo. Passwordbar.

Check the Cloudant Login certification document: Https://docs.cloudant.com/api/authn.html.

Can find Cloudant login authentication related interface has three:


Here we use the Post method for cookie login authentication. Combined with the above if username and password:

To access the URL for the Foo.cloudant.com/_session header information for the content-type:application/x-www-form-urlencoded parameter is name = foo, password = bar

If the interview is successful, we will be able to obtain a cookie in the network response for other operations to be used later. Obviously, this request has nothing to do with JSON. You should use Stringrequest. There are two ways to construct stringrequest:

Public stringrequest (int method, String URL, listener<string> Listener, Errorlistener errorlistener) public Stringrequest (String URL, listener<string> Listener, Errorlistener Errorlistener)
The second method only has get request talent enough to use, the first method of the parameter can be used to define the request type, here we need to post, so should use the first construction method:

Stringrequest request = new Stringrequest (                Request.Method.POST,                "Http://foo.cloudant.com/_session",                New Response.listener<string> () {                    @Override public                    void Onresponse (String s) {  //received a successful response will trigger this                    }                },                new Response.errorlistener () {                    @Override public                    void Onerrorresponse (Volleyerror volleyerror) {//The connection error will be triggered here                    }                }        );

In the above code, we have successfully constructed a stringrequest, which already includes the post and the correct URL we need, and also joins the network response listener at the same time. However, the lack of documentation requires our header information and the number of references. Stringrequest does not provide the definition of this information in the construction, which is also different from other frequently used web tools, the new contacts may be very inappropriate, through the replication of Stringrequest two methods can be put into the information. This request is intact:

Stringrequest request = new Stringrequest (Request.Method.POST, "Http://foo.cloudant.com/_se  Ssion ", new Response.listener<string> () {@Override public void                    Onresponse (String s) {}}, new Response.errorlistener () {                @Override public void Onerrorresponse (Volleyerror volleyerror) {}  }) {@Override public map<string, String> getheaders () throws Authfailureerror {                Set header information map<string, string> Map = new hashmap<string, string> ();                Map.put ("Content-type", "application/x-www-form-urldecoded");            return map;                } @Override protected Map<string, string> Getparams () throws Authfailureerror {//Set of parameters map<string, string> map = new Hashmap<strinG, string> ();                Map.put ("name", "foo");                Map.put ("Password", "bar");            return map; }        };

Compared to the first time of our construction process, this time more than two copies of the method to set the header information and parameters, very easy bar. This time the request is basically complete, but there is a very important thing missing. Our login authentication is to get back our own cookie, and if we can't get a cookie, how the correct request format is a waste of effort. You want to get a cookie. There is also a way to get it through replication:

            @Override            protected response<string> parsenetworkresponse (Networkresponse Response) {for                (String s: Response.headers.keySet ()) {                    if (s.contains ("Set-cookie")) {                        Mcookie = Response.headers.get (s);                        break;                    }                }                return Super.parsenetworkresponse (response);            }
After the network request succeeds. The service side returns the response information. The cookie information we need is located in these responses, through the traversal of the corresponding answer information. It's very convenient to find the information we need.

Here, our login authentication request is constructed, and the last thing we need to do is throw this stringrequest into our request queue:

Mqueue.add (Request);
When the network is unobstructed. It's very fast. Get cookie information.


3. View Test Documents

After the registration cloudant is successful, cloudant will create a default database--crud in our account, with a row of test data welcome saved.

watermark/2/text/ahr0cdovl2jsb2cuy3nkbi5uzxqvywlyazawma==/font/5a6l5l2t/fontsize/400/fill/i0jbqkfcma==/ Dissolve/70/gravity/center ">

Let's use volley to interview this data. Consult the Cloudant API documentation for documents related to discovery:

watermark/2/text/ahr0cdovl2jsb2cuy3nkbi5uzxqvywlyazawma==/font/5a6l5l2t/fontsize/400/fill/i0jbqkfcma==/ Dissolve/70/gravity/southeast ">

The content of the file (data) can be obtained by matching the correct URL with a simple GET request. Of course. The premise of all this is that we have mastered the correct cookie data. Then we need to:

1. The request header data includes the correct cookie information 2. Interview the right URL3. Request Type: GET
If we log on to the authentication in the previous step, we save the cookie information in the Mcookie string variable.

And the URL we need to access through the document can also be obtained by the path to the database name + document name, that is, foo.cloudant.com/crud/welcome.

Everything. Using stringrequest:

        Stringrequest request = new Stringrequest (                "Http://foo.cloudant.com/crud/welcome",                new Response.listener <String> () {                    @Override public                    void Onresponse (String s) {                    }                },                new Response.errorlistener ( {                    @Override public                    void Onerrorresponse (Volleyerror volleyerror) {                    }                }        ) {            @Override Public            map<string, string> getheaders () throws Authfailureerror {                map<string, string> Map = new Ha Shmap<string, string> ();                Map.put ("Cookie", Mcookie);                return map;            }        };        Mqueue.add (Request);

In Onresponse we receive a JSON-form string welcome this data:

watermark/2/text/ahr0cdovl2jsb2cuy3nkbi5uzxqvywlyazawma==/font/5a6l5l2t/fontsize/400/fill/i0jbqkfcma==/ Dissolve/70/gravity/southeast "style=" font-size:12px ">

A simple network request stringrequest completely processed. The use is also relatively simple, introduced here.

The Jsonobjectrequest application method is described below.


4. Create new data using Jsonobjectrequest
First look at the construction method of Jsonobjectrequest:
Public jsonobjectrequest (int method, String URL, jsonobject jsonrequest, listener<jsonobject> Listener, Errorlistener errorlistener) public jsonobjectrequest (String URL, jsonobject jsonrequest, listener<jsonobject> Listener, Errorlistener Errorlistener)
The first method takes this as: Request method, Access Url,json data object, request successful listener, request failed listener. Another kind of construction method. If the jsonrequest is empty, then the method is itself active as get. When not empty, you switch to post on your own initiative. Other parameters mean the same.

Cloudant's documentation (https://docs.cloudant.com/api/documents.htmlRequires that the document be created using the post or Put method. The data you carry is in JSON format. In this way, Stringrequest seems to be out of reach, we need to use to volley also has a request type: Jsonobjectrequest.

The following is an example of creating data by post, and by looking at the Cloudant documentation:

1. Visit the URL path for database folder 2. Content-type was asked to be application/json3. Data that is carried is required as JSON data

Now that the method requires post, we create the data again. Sure the data content is not empty, so we choose a different construction method. First, create a JSON object:

        Jsonobject jsonobject = new Jsonobject ();        Jsonobject.put ("_id", "TestInfo");        Jsonobject.put ("Person", "foo");        Jsonobject.put ("Phone", "bar");

In the Cloudant data storage system, the ID can be specified by the developer. The next step is to construct and request Jsonobjectrequest:

        Jsonobjectrequest request = new Jsonobjectrequest (                "Http://foo.cloudant.com/crud",                Jsonobject,                new Response.listener<jsonobject> () {                    @Override public                    void Onresponse (Jsonobject jsonobject) {                    }                },                new Response.errorlistener () {                    @Override public                    void Onerrorresponse (Volleyerror volleyerror) {                    }                }        ) {            @Override public            map<string, string> getheaders () throws Authfailureerror {                map<string, string> map = new hashmap<string, string> ();                Map.put ("Cookie", Mcookie);                return map;            }        };        Mqueue.add (Request);

The Jsonobject data is not empty, so the request is actively switched to Post,url for the same path as the database where the data is to be created. Then the listener that requests the results, and finally don't forget to take the cookie. Otherwise, authentication errors will occur.

At last. The constructed request is dropped into the queue. Dispatch is handled by volley. It is better to look back at this time to see which elements of the previously analyzed request are not difficult to find. JSON request for volley. There is no special setting for the Content-type. Jsonobjectrequest is inherited from the jsonrequest. And Jsonrequest has helped us through this action:

    @Override public    String Getbodycontenttype () {        return protocol_content_type;    }

PS: Set Content-type can also be getbodycontenttype this function through the replication, instead of always troublesome to use the map in the GetHeader to set up, the two settings are the same effect. And you don't have to worry about coding formats. Since the default is Utf-8:

    /** Charset for request. */    private static final String Protocol_charset = "Utf-8";    /** Content type for request. *    /private static final String Protocol_content_type =        String.Format ("Application/json; charset=%s ", Protocol_charset);

Here, the relevant usage of the JSON request is also covered. The next section will analyze the logic order of the volley request from the source code point of view, assuming that we need to write our own request type, which functions need to be replicated. And what needs attention.


Source


For volley and cloudant many other communication details, see Cloudantvolley Project: Https://github.com/airk000/CloudantVolley


Android App development: Network Tools--volley (i)

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.