Android Application Development: network tool-Volley (1), androidvolley

Source: Internet
Author: User
Tags cloudant

Android Application Development: network tool-Volley (1), androidvolley
Introduction


The Internet has always been a blind spot for me. I took some time to learn how to use the Volley network tool, and learned more through the source code. In Android development, there are many mature network tools. Android comes with HttpClient, okhttp, and the ion open-source project created by koush, and google later joins Volley in the Android project source code. The reason for using Volley is that Volley is simple to use and has clear logic. Even if a problem occurs during the debugging process, it can be quickly located through the source code.


Volley Compilation


Because I am used to using Gradle architecture applications, I tried to find out if I could use the gradle configuration file for library dependency for the first time. Unfortunately, no. However, even with this Volley library, it is easy to add it to our project.


First, ant compilation tools are required. If the Android system source code is available, Volley is under the frameworks/volley directory. If you do not have the Android source code, you can clone the Volley source code from the Android Repository:

git clone https://android.googlesource.com/platform/frameworks/volley
Unfortunately, the volley Library source code Android is not hosted on its Github account, so it can only be cloned on googlesource. Of course, FQ is required in China.

Volley source code structure:


After cloning, ant can be easily used for compilation. Of course, if it is in the complete Android source code, it can also be compiled directly through make, but it will take a lot of time. Here, ant compilation is used as an example to execute:

ant jar
Result:


In this way, the jar package is generated, which is very convenient. You can add it to the project.

Volley usage


Volley's network Request parent class is Request <T>, which can be provided to developers for inheritance. It also provides several types of common requests in development. Two types are described below: StringRequest and JsonObjectRequest.

To be closer to actual use, Volley and Cloudant will be used as an example below. Cloudant is a cloud service provider that provides developers with free cloud storage and cloud database services. This article does not describe the process such as its registration. It is very simple. Start with Logon:


1. Apply for a network Request queue

One of Volley's major features is that all network requests do not need to be executed by the developer, but are thrown into the Volley Request queue after the request construction is complete, and the queue requests in turn, this saves a lot of trouble, and developers do not have to worry about whether network requests will conflict with each other and whether they will be in the main thread. Volley's network queues have all helped us solve this problem.

Generally, an Application can have only one request queue (corresponding to the Application) if there are not many network requests, an Activity corresponds to a network Request queue. The following code shows how to apply for a Volley network Request queue:

RequestQueue mQueue;mQueue = Volley.newRequestQueue(getApplicationContext());

In this way, a network Request queue is successfully applied. If there is only one request queue, you can apply in the Application.


2. log on to Cloudant with Volley

Assume that you have successfully registered. The login name is foo and the password bar is used.

Go to the logon authentication document of Cloudant: https://docs.cloudant.com/api/authn.html. You can find that there are three interfaces related to Cloudant logon authentication:


Here we use the POST method for cookie login authentication. Based on the preceding username and password, we can see that:

The url to be accessed is foo.cloudant.com/_sessionheader. Content-Type: application/x-www-form-urlencoded. The parameter name = foo, password = bar

If the access succeeds, we can obtain the cookie in the network response for other subsequent operations. Obviously, this request has nothing to do with json. StringRequest should be used. StringRequest has two constructor methods:

public StringRequest(int method, String url, Listener<String> listener, ErrorListener errorListener)public StringRequest(String url, Listener<String> listener, ErrorListener errorListener)
The second method can be used only for GET requests. The method parameter of the first method can be used to customize the request type. Here we need POST, so we should use the first constructor:

StringRequest request = new StringRequest (Request. method. POST, "http://foo.cloudant.com/_session", new Response. listener <String> () {@ Override public void onResponse (String s) {// triggered here after a successful Response is received}, new Response. errorListener () {@ Override public void onErrorResponse (VolleyError volleyError) {// a connection error will be triggered here }});

In the above Code, we have successfully constructed a StringRequest, which includes the POST and the correct URL we need, and added the network response listener. However, our header information and parameters are missing. StringRequest does not provide the definition of this information in the construction. This is also different from other commonly used network tools. New contacts may not be suitable, you can put the information in two methods of rewriting StringRequest. Below we will improve this request:

StringRequest request = new StringRequest (Request. method. POST, "http://foo.cloudant.com/_session", 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 the 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 the parameter Map <String, String> map = new HashMap <String, String> (); map. put ("name", "foo"); map. put ("password", "bar"); return map ;}};

Compared to our first construction process, this time we have two more rewrite methods to set the header information and parameters, which is very easy. At this time, the request is basically completed, but there is no other important thing. Our login authentication is to get our own cookie. If we cannot get the cookie, what a correct request format is in vain. If you want to get a cookie, you can use another method to retrieve it:

            @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 server returns the response information, and the Cookie information we need is searched through the traversal of the response information in the response information, we can easily find the information we need. At this point, the login authentication request is constructed, and the last thing we need to do is to throw the StringRequest to our request queue:

mQueue.add(request);
When the network is smooth, the Cookie information will soon be available.


3. view the test document

After successfully registering Cloudant, Cloudant creates a default database named crud in our account, which stores a row of test data welcome.


Let's use Volley to access this data. Check the Cloudant API documentation Documents and find the following:


You can GET the file (data) content through a simple GET request with the correct URL. Of course, the premise is that we have mastered the correct Cookie data. Then, we need:

1. The request header data contains the correct Cookie Information 2. Access the correct URL3. request type: GET
Assume that the Cookie information is stored in the mCookie string variable after the previous login authentication. The URL we need to access can also be obtained through reading the document path is the database name + document name, that is, foo.cloudant.com/crud/welcome. Everything is ready. 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 HashMap<String, String>();                map.put("Cookie", mCookie);                return map;            }        };        mQueue.add(request);

In onResponse, we will receive the json string of the welcome data:

Simple Network request StringRequest can be completely processed, and its usage is relatively simple. Here we will introduce it. The following describes the JsonObjectRequest application method.


4. Use JsonObjectRequest to create new data
First, let's take a look at the JsonObjectRequest construction method:
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 includes the request method, access URL, Json data object, request success listener, and request failure listener. In the second constructor, if jsonRequest is empty, the method is automatically GET, and if not empty, the automatic switch is POST. Other parameters have the same meaning.

Cloudant documents (https://docs.cloudant.com/api/documents.html) require that the creation of documents can be performed using the POST or PUT method, and the data carried is in json format. In this way, StringRequest seems to be insufficient. We need to use another built-in request type of Volley: JsonObjectRequest. The following example uses the POST method to create data. by viewing the Cloudant document, we can see that:

1. The accessed URL path is the database directory. 2. The Content-Type must be json data carried by application/json3.

Since the method requires POST, we create data again, and certainly the data content will not be blank, so we choose the second constructor. 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, IDS can be specified by developers. Next, 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);

JsonObject data is not empty, so the request method is automatically switched to POST, the url is the path of the database where the data to be created is located, and then the listener of the Request result. Finally, don't forget to bring the Cookie, otherwise, an authentication error occurs. Finally, the constructed request is thrown into the queue for scheduling and processing by Volley. At this time, let's look back at the elements required by the previously analyzed request. It is not difficult to find that Content-Type is not set in Volley's json request. JsonObjectRequest inherits from JsonRequest, and JsonRequest has completed this action for us:

    @Override    public String getBodyContentType() {        return PROTOCOL_CONTENT_TYPE;    }

PS: You can set the Content-Type by rewriting the getBodyContentType function, instead of using the map in the getHeader to set it. The effects of the two methods are consistent.You do not need to worry about the encoding format, because the default value 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);

At this point, the usage of the Json request is also described. In the next section, we will analyze the logic sequence of Volley requests from the source code perspective. If we need to write our own request types, which functions need to be rewritten, and what you need to pay attention.


Source code


For more information about Volley and Cloudant, see CloudantVolley project: https://github.com/airk000/CloudantVolley



How to Develop android network applications

I just finished a project. In fact, the general idea of developing such applications is like this. First you have your server. I am using an Amazon cloud host. You can apply for one, but it is not free, but not expensive. With the host, you can design a database first, that is, tables, then you need to select a server development technology. Currently, PHP and JSP are popular. I am using PHP. You can select an MVC-based framework to develop the interface to be accessed by android (in other words, it is the URL), and it is best to return it in JSON format, database query results: This is the development of the server, and then the client. Don't worry, there is a developed framework, namely Volley. This framework is very good and encapsulates network requests, good cache mechanism, import Volley. Jar is used directly. For more information, see the blogs on the Internet. The essence is to use Volley to parse the network JSON data, and the parsed data will be displayed on your control, which is actually very simple.


Android simple application development: How to dynamically set the ip address and port number of a PC in the same lan?

First, you need to enter the ip address. The port should use EditText instead of TextView. You only need to get edittext. gettext (). tostring () in the onClick event of the button (). Obtain the input string, and then call the method in the Utils package

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.