From the previous article together to develop the Android weather software two of the time will be nearly half a month, between always because of something and not updated really sorry, recently will speed up the pace of the update, in order to finish the 2015 before the arrival of this series of blog posts, In the previous chapter we have used the Litepal framework to build the database we need, the content of this chapter will be mainly about the network to obtain data from the Chinese Weather Network communication operations, before the students who have studied Android development should know that Android to achieve Internet communication there are two main methods, A way to use HttpURLConnection, a httpclient approach, and today we will use the volley framework to complete our network communications service in a different way than the two.
The volley framework was introduced in 2013 at the Google I/O conference with a new network communication framework. Volley is very simple and easy to use, in the communication performance has also made a large adjustment, its design goal is very suitable for the data volume is very small, but the traffic is frequent network operation, also more suitable for our software bar.
first, how to obtain dataHow to get information about all provinces in the country, we will return the names and codes of all provinces in China as soon as we visit the following URL http://www.weather.com.cn/data/list3/city.xml, as shown below. 01| Beijing, 02| Shanghai, 03| Tianjin, 21| Zhejiang and so on, we can see the city and its code by the | number separated, between the provinces and provinces, separated by the number, remember this structure. After that, a regular expression is used to intercept it. How to see the city information saved in Zhejiang, in fact, is very simple, just need to visit the following URL http://www.weather.com.cn/data/list3/ City21.xml, that is, only need to add provincial code to the city behind the can, the server will return data 2101| Hangzhou, 2102| Ningbo, 2103| Wenzhou and so on. in the same way, if we want to visit the following counties and cities in Hangzhou, we only need to add 2101 to city, as shown below Http://www.weather.com.cn/data/list3/city2101.xml. so we can know how to get the information of the national provincial city, so how to get the weather of a specific city? Take Hangzhou as an example his county code is 210101, then visit the following URL Http://www.weather.com.cn/data/list3/city210101.xml will return a very simple data 210101| 101210101, the following is the Hangzhou of the corresponding weather code, and then we use this to get the code can be accessed to the URL http://www.weather.com.cn/data/cityinfo/101210101.htm, Note that this URL suffix is HTML, not XML, when writing code, do not write wrong, so that the server will be Hangzhou weather information has been JSON format data back to us, as shown below. {"Weatherinfo": {"City": "Hangzhou", "Cityid": "101210101", "Temp1": "1 ℃", "Temp2": "10 ℃", "Weather": "Cloudy to Clear", "IMG1": " N1.gif "," Img2 ":" D0.gif "," Ptime ":" 18:00 "}}
second, how to realize network communicationWe now know the specific address of the URL visited, then how to achieve real network communication through our software, then I will first use the Httpurlconnction method to achieve the network data acquisition, the specific code is as follows.
Package Com.melhc.util;import Java.io.bufferedreader;import Java.io.inputstream;import java.io.InputStreamReader; Import Java.net.httpurlconnection;import Java.net.url;public class Httputil {/* * Get data from the server for county and city */public static void send HttpRequest (final String address,final Httpcallbacklistener listener) {New Thread (new Runnable () {@Overridepublic void Run () {//TODO auto-generated method Stubhttpurlconnection connection = null;try {//Create a URL object url url = new URL (address);// Gets the httpurlconncetion instance through the URL object connection = (httpurlconnection) url.openconnection ();// The method used to set the HTTP request is the Get method Connection.setrequestmethod ("get");//Customize some properties, such as setting the connection timeout, The number of milliseconds to read timeout connection.setconnecttimeout (8000); Connection.setreadtimeout (8000);//Gets the input stream returned by the server InputStream in = Connection.getinputstream ();//converts the resulting input stream into a string string BufferedReader reader = new BufferedReader (New InputStreamReader ( In, "Utf-8")); StringBuffer response = new StringBuffer (); String Line;while (line = Reader.readline ())! = null) {response.append (line);} Logutil.i ("Httputil", "------------------>" + response.tostring ()); if (listener! = null) {Listener.onfinish ( Response.tostring ());}} catch (Exception e) {//Todo:handle exceptionif (listener! = null) {Listener.onerror (e);}} finally {if (connection! = nul L) {connection.disconnect ();}}}). Start ();}}
The above code should be relatively straightforward, because the network communication operation is a time-consuming operation, so it cannot be used in the main thread, so we opened a new sub-thread to get the data! Careful friends will find the above parameters in addition to the target access URL, but also passed in a Httpcallbacklistener object, this is why use it? Here is a callback mechanism, because the child thread is not allowed to have a return object, and the data we return may be used in the method of another class, then how to pass the data in two classes, then we will apply to the callback mechanism. first create a Httpcallbacklistener interface
Package com.melhc.util;/* * network connection back-up interface */public interface Httpcallbacklistener {void onfinish (String response); void OnError (Exception e);}
then the method as a parameter passed into our network communication class, in fact, his implementation is the same as our common Android Onclicklistener implementation, and then the specific implementation of this interface in the use of this class where the realization of the data obtained in the network communication, This interface is actually a bridge connecting two classes.
Httputil.sendhttprequest (Address, new Httpcallbacklistener () {@Overridepublic void OnFinish (String response) {//TODO auto-generated method Stubboolean result = False;if ("Province". Equals (type)) {result = Utility.handleprovicesresponse ( Weatherdb, response);} else if ("City". Equals (type)) {result = Utility.handlecitiesresponse (Weatherdb, response,selectedprovince);} else if (" County ". Equals (Type)" {result = Utility.handlecountiesresponse (Weatherdb,response, selectedcity);}
This is the implementation of the use of the class, this class after our blog post specific introduction, here we just notice in the main thread we only instantiate the Httpcallbacklistener interface, through the response parameter transfer continue to complete the next method. Traditional network communication method to this is finished, is not feel still quite troublesome, also have to use what callback mechanism, in the volley can not need, others have helped us package well. Iii. Volley realization of network communicationthen we begin to formally use the volley to complete the above touch of the same communication process, only three steps to complete the network to send and respond! First of all, you have to download the volley jar file, and import your own program! volley.jar:http://download.csdn.net/detail/u013900875/8279223. Then follow these three steps to go!
1. Create a Requestqueue object.
2. Create a Stringrequest object.
3. Add the Stringrequest object to the Requestqueue.
& nbsp The specific code implementation is as follows
Requestqueue mqueue = Volley.newrequestqueue (Getapplicationcontext ()); Stringrequest stringrequest = new Stringrequest (address,new response.listener<string> () {@Overridepublic void Onresponse (String response) {logutil.i ("TAG", "---------------->" +response); Boolean result = False;if ("province". Equals (type)) {result = Utility.handleprovicesresponse (weatherdb,response);} else if ("City". Equals (type)) {result = Utility.handlecitiesresponse (Weatherdb,response, selectedprovince);} else if ("County". Equals (type)) {result = Utility.handlecountiesresponse (Weatherdb,response, selectedcity);} if (result) {//returns the main thread processing logic runonuithread (new Runnable () {@Overridepublic void Run () {//TODO via the Runonuimainthread method) Auto-generated method Stubcloseprogressdialog (); if ("Province". Equals (Type)) {queryprovinces ();} else if ("City". Equals (type)) {querycities ();} else if ("County". Equals (Type)) {querycounties ();}}});}}, New Response.errorlistener ( {@Overridepublic void Onerrorresponse (volleyerror error) {LOgutil.i ("TAG", "-------------------->" + error); Runonuithread (new Runnable () {@Overridepublic void Run () {//TODO Au to-generated method//stub//closeprogressdialog (); Toast.maketext (Getapplicationcontext (), "Load Data failed!" ", Toast.length_short). Show ();});}); Mqueue.add (stringrequest);
we can find that the volley framework is really a lot simpler, do not need us to set some HTTP communication properties and some callback methods, let us only to care about how to handle the returned data can be, then we will analyze each step of volley three steps.
Requestqueue Mqueue = volley.newrequestqueue (context);
The first step is to get to a Requestqueue object, note that the Requestqueue is a request queue object, it can cache all HTTP requests, and then follow a certain algorithm to issue these requests concurrently.
Stringrequest stringrequest = new Stringrequest (address, new response.listener<string> () { @Override Public void Onresponse (String response) { log.d ("TAG", response); } }, new Response.errorlistener () { @Override public void Onerrorresponse (volleyerror error) { log.e ("TAG", Error.getmessage (), error); } });
The second step to send an HTTP request, where to pass three parameters, the first is to visit the destination website URL, the second is the successful callback to get the data after the method, the third is the failure callback to get the data method, is not very simple, save us the process of creating an interface.
Finally, the Stringrequest object is added to the requestqueue inside it can be, the work done! OK, the content of this lesson is here, but also hope that you can continue to support the series of blog posts, your support is my greatest motivation to write down! The content of today's network communication is over, and the next blog post will soon meet you.
One up to develop the weather software for Android (iii)