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

Source: Internet
Author: User
Tags cloudant

Introduction


Network has been my personal blind spot, a while ago to take time to learn a bit volley network tools to use, but also through the source of further learning, have some experience to share. In Android development, a lot of mature network tools, Android comes with HttpClient, as well as okhttp, as well as the Koush great God created ion open source project, and then Google later added to the source of Android project volley. Why use volley, is because volley use simple, logic clear, even in debugging process problems, also can quickly through the source to locate.


Volley compiling


Because I'm used to using the Gradle framework application, I try to find out if I can rely on the Gradle configuration file for the first time when I want to use volley. Unfortunately, there is no. But even so volley's library is easy to make to join our project.


First requires the Ant compiler tool, and then if there is an Android system source, volley in the Frameworks/volley directory. If there is no Android source code, but also very good to do, you can separate from the Android storage to clone the volley source code:

git clone Https://android.googlesource.com/platform/frameworks/volley
Unfortunately, the volley library's source Android is not hosted on its GitHub account, so it can only be cloned on the Googlesource, of course, in the country will need to FQ first.

For volley source structure:


After cloning successful, you can easily use ant to compile, of course, if it is under the full Android source code, can also be directly compiled by make, but the time will inevitably grow a lot. Here, using ant compilation as an example, executes:

Ant Jar
Results:


This allows the jar package to be generated, which is handy, and is then added to the project for use.

Volley use


Volley's network request parent class is REQUEST<T>, which can be provided to the developer for inheritance, as well as some of the types of requests commonly used in the development, which are described below in two: Stringrequest and Jsonobjectrequest.

To get closer to the actual use, the following will use volley to communicate with Cloudant to do an example. Cloudant is a cloud services business that provides developers with free cloud storage and cloud database services. The process of registering and so on is not described in this article, very simple. Start directly from Login:


1. Request a queue for network requests

A big feature of volley is that all Web requests do not need to be executed by the developer 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 hassle and the developer does not have to worry about whether the network request will conflict, whether it will be in the main thread, These volley network queues have helped us to solve the problem.

In general, an application that is not particularly frequent if the network request can have only one request queue (corresponding to application), if very many or other circumstances, it can be an activity corresponding to a network request queue, the specific situation of specific 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, and if there is only one, you can request it in application.


2. Login with Volley Cloudant

If you have successfully registered, login foo, password bar.

Check the Cloudant Login certification document: Https://docs.cloudant.com/api/authn.html. You can find the Cloudant login authentication related interface has three:


Here we use the Post method for cookie login authentication. With the user name and password assumed above, you know:

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

If the access is successful, we can get a cookie in the network response for other operations to be used later. Obviously, this request has nothing to do with JSON, and there are two ways to construct the Stringrequest,stringrequest:

Public stringrequest (int method, String URL, listener<string> Listener, Errorlistener errorlistener) public Stringrequest (String URL, listener<string> Listener, Errorlistener Errorlistener)
The second method can only be used with a GET request, the method parameter of the first can be used to customize the request type, here we need post, so we 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 that already contains the post and the correct URL we need, as well as adding a network response listener. However, there is also a lack of documentation that requires our header information and parameters. Stringrequest does not provide the definition of this information in the construction, which is also different from other common network tools, the newly contacted students may be very inappropriate, through the replication of the Stringrequest two methods can be put into the information. Below to refine this request:

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 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, it is very easy. This time the request is basically complete, but there is a lack of another very important thing, our login authentication is to take back their own cookies, if not to obtain cookies, how the correct request format is a waste of effort Ah, To get a cookie is also obtained by means of another method of 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 is successful, the service side returns the response information, and we need the cookie information in these responses, through the response information through the search, it is 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, cookie information is quickly available.


3. View the test document

After the successful registration of Cloudant, Cloudant will create a default database--crud in our account, which holds a row of test data welcome.


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


With a simple GET request with the correct URL to get the file (data) content, of course, all this is the premise that we have mastered the correct cookie data. So, we need:

1. The request header data contains the correct cookie information 2. Access the correct URL3. Request Type: GET
Let's say we saved the cookie information in the Mcookie string variable after we logged in to the authentication in the previous step. And we need to access the URL through the lookup document can also be obtained by the path to the database name + document name, that is foo.cloudant.com/crud/welcome. Ready to use 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:

The Simple network request stringrequest completely processing, the use is also relatively simple, introduces 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 parameter is: Request method, Access Url,json data object, request successful listener, request failed listener. In the second construction method, if the jsonrequest is empty, the method is automatically switched to post, and the other parameters have the same meaning.

Cloudant's documentation (https://docs.cloudant.com/api/documents.htmlrequired to create a document can be done using the post or Put method, with the data being carried in JSON format. In this way, Stringrequest seems to be out of reach, we need to use another volley request type: Jsonobjectrequest. The following is an example of creating data by post, and by looking at the Cloudant documentation:

1. The URL of the access path is database directory 2. Content-type was asked to be application/json3. Data that is carried is required as JSON data

Since the method requires post, we are creating the data, and the data content is not empty, so we choose the second 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 automatically switched to Post,url for the database where you want to create the path, and then the listener to request the results, and finally do not forget to take the cookie, or there will be a certification error. Finally, the construction completed request is dropped into the queue and dispatched by volley. It's time to look back and see what elements are needed for the previously analyzed request, and it's not hard to see that the volley JSON request does not have a special setting for Content-type. Jsonobjectrequest is inherited from Jsonrequest, and Jsonrequest has done this for us:

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

PS: Set Content-type can also be getbodycontenttype this function through the replication, without always troublesome to use the map in the GetHeader to set, the two settings are the same effect. And don't worry about the encoding format, because 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 logical order of the volley requests from the source point of view, and if we need to write our own request types, what functions need to be replicated and what needs to be noticed.


Source


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


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

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.