Android Learning Note (four or five): Internet communication-httpclient, XML parsing (web)

Source: Internet
Author: User
Tags response code

A few days ago, Android released 4.0 Icecream, yesterday on the Internet found begining Book edition 3 version, compared to a bit, or there is a considerable change, not only to increase the portion of the tablet, there are some revisions to the original chapters, before and after the adjustment and so on. First, according to the Order of Edtion 2, look at the same chapter Edtion 3, and then look Back edition 3 Chapter 24, 36 (E2 26), the number of pages, 27, 28, 29, 44, 45, 46, 47 several new chapters. Also changes the emulator to Android 2.3, adapting to possible new changes.

Access to the Internet is an important user of the device, previously learned how to embed WebKit, and we can access intenet through the API. Android offers Apache HttpClient libraries, based on which other protocols can be considered in the format of HTTP encapsulation, such as Xml,json. The details of the HTTP client can be obtained in http://hc.apache.org/.

Android provides three XML parsers: 1, traditional parser DOM (org.w3c.dom), 2, SAX parser (Org.xml.sax), 3, Previous Android Learning Note (38): Use Xmlpullparser in resource resource (above). A JSON parser (Org.json) is also available. Third-party parsers, of course, can also be used. The steps to implement are as follows:

    1. The object that creates the HttpClient interface can be created by defaulthttpclient.
    2. Requests and HttpRequest judgement, including Httpget,httppost, execute the request through execute ().
    3. You can use the Httpresponsed object to process the return, with response code (for example, 200, which is OK), HTTP prime, and you can carry ResponseHandler as a parameter in execute (), which returns response Body, but this method is feasible but not recommended, because generally speaking we should response code.

Here is a small example of a weather widget, using httpclient, which is to send a request to a URL (Google's Weather Query Web page) with the HttpGet, return the weather information in XML format, analyze from it, and pass the result WebKit Browser the way the program, below is looking for the return of Guangzhou weather. In the example, the first study of the use of HttpClient, the second also learn the parsing of XML, the use of the DOM parser, through the nodelist and element to analyze.


<xml_api_reply version= "1" >
<weather module_id= "0" tab_id= "0" mobile_row= "0" mobile_zipped= "1" row= "0" section= "0" >
<forecast_information><!--find location information, only the part that prepares the analysis--
... ...
<postal_code data= "Guangzhou"/>
<forecast_date data= "2011-10-27"/>
</forecast_information>
<current_conditions><!--gives the current weather conditions, showing only the part that is ready for analysis--
<condition data= "Partly cloudy"/>
<temp_c data= "/>"
<icon data= "/ig/images/weather/partly_cloudy.gif"/>
<wind_condition data= "Wind: North, Wind Speed: 2 m/S"/>
</current_conditions>
<forecast_conditions><!--give the day's weather forecast--
<day_of_week data= "Thursday"/>
<low data= "/>"
<icon data= "/ig/images/weather/mostly_sunny.gif"/>
<condition Data= "To clear the main"/>
</forecast_conditions>
<forecast_conditions><!--give tomorrow's weather forecast--
... ...
</forecast_conditions>
<forecast_conditions><!--give weather forecast--
... ...
</forecast_conditions>
<forecast_conditions><!--give a third-day weather forecast-
... ...
</forecast_conditions>
</weather>
</xml_api_reply>

The program code is as follows:

(This interface belongs to IGoogle's private interface, has been closed, you can find other weather APIs, such as http://www.wunderground.com/weather/api/.) Wei, 2012.9)

public class Chapter25test1 extends activity{
Private WebView browser = null; Use WebView to compose the displayed content
PrivateHttpClientclient = null;
Private list<forecast> forecasts = new arraylist<forecast> (); Use list to save weather conditions for the next few days
Private Currentweather currentcondition = null; Save immediate weather conditions and location time
Private String format = "Http://www.google.com/ig/api?hl=zh-cn&weather=%1s"; Query API interface for Google XML weather Information

protected void OnCreate (Bundle savedinstancestate) {
Super.oncreate (savedinstancestate);
Setcontentview (R.LAYOUT.CHAPTER_25_TEST1);
Browser = (WebView) Findviewbyid (R.id.c131_webkit);
Step 1, create the HttpClient interface object, can be created by defaulthttpclient.
client = new Defaulthttpclient ();
}

protected void Onresume () {
Super.onresume ();
Updateforecast ("Guangzhou"); Step 2, request weather information from Guangzhou to the Internet, get information, and present
}

protected void OnDestroy () {
Super.ondestroy ();
Step 3, Release httpclient resources, this step is not detailed tracking, as a literal estimate if the connection is not a reply, when the activity destroy, terminate the connection
Client.getconnectionmanager (). Shutdown ();
}

Step 2, request weather information from Guangzhou to the Internet, get information, and present
private void Updateforecast (String citycode) {
String url = String.Format (format, citycode);
Step 2.1, generate the HttpGet request and send it to the Internet via execute (), and get the return value in ResponseHandler.
httpget GetMethod = new HttpGet (URL);
try{
responsehandler<string> responsehandle = new Basicresponsehandler ();
String responsebody = client.Execute (GetMethod, Responsehandle);
Buildforecasts (responsebody); Step 2.2 Get the weather information from the return
String page = Generatepage (); Step 2.3 rendered via HTML in WebKit browser
Browser.Loaddatawithbaseurl(NULL, page, "text/html", "UTF-8", null);
}catch (Throwable t) {
Toast.maketext (This, "Request failed:" + t.tostring (),). Show ();
}
}
Step 2.2 Get the weather information from the return, note the wording of this throws exception
private void Buildforecasts (String raw)throws Exception{
Documentbuilder builder = documentbuilderfactory.newinstance (). Newdocumentbuilder ();
Document doc = builder.parse (new InputSource (new StringReader (raw)));
Get instant weather information and location, time information, in the same way as the future weather forecast, more cumbersome, skip, information stored in the Currentcondition
.... ....

For Xml<node_name node_attribute=attribute_valule> Node_vaule </node_name>
NodeList furcondition = doc.getElementsByTagName("Forecast_conditions");
There are future 4th weather forecasts, respectively taken out
for (int i = 0; i < furcondition.getlength (); i + +) {
Element e = (element) furcondition.item (i);
Addweather (e);
}
}
private void Addweather (Element e) {
Forecast FC = new Forecast (Getweatherattribute (E, "Day_of_week"),
Getweatherattribute (E, "low"),
Getweatherattribute (E, "high"),
Getweatherattribute (E, "icon"),
Getweatherattribute (E, "condition"));
Forecasts.add (FC);
}

The following is a reading of the required information from each set of element, plus the addition of a node.getattributes (). getNamedItem ("Data") if the love is obtained using node, such as E.getfirstclide (). Getnodevalue () to get the property value carried
Private String Getweatherattribute (Element E, string name) {
NodeList t = e.getElementsByTagName(name);
Element a = (element) t.item (0);
Return a.getattribute("Data");
}

Step 2.3 rendered via HTML in WebKit browser
Private String Generatepage () {
StringBuilderBufresult = new StringBuilder ("Bufresult.Append("...//Show instant messages
Bufresult.append ("<table><tr><th width=\" 25%\ ">Time</th>" +
"<th width=\" 25%\ "> Temperature </th><th colspan=\" 2\ "width=\" 50%\ "> Weather conditions </th></tr>");
for (Forecast forecast:forecasts) {
Bufresult.append ("<tr><td align=\" Center\ ">");
Bufresult.append (Forecast.getdate ());
Bufresult.append ("</td><td align=\" Center\ ">");
Bufresult.append (Forecast.gettemperature ());
Bufresult.append ("</td><td align=\" right\ ">");
Bufresult.append (Forecast.getcondition ());
Bufresult.append ("</td><td align=\" left\ ">Bufresult.append (Forecast.geticon ());
Bufresult.append ("\" ></td></tr> ");
}
Bufresult.append ("</table></body>return bufresult.tostring ();
}
Private Class forecast{
..../* Store weather information and provide get get method */....
}
Private Class currentweather{
..../* Store current weather, time, location, and provide get get method */....
}
}

Get local weather by latitude

In the Google Weather API, you can also enter latitude and longitude in the format: http://www.google.com/ig/api?hl=zh-cn&weather=,,, 23080000,113170000, this is the latitude and longitude of Guangzhou. Android can get the latitude and longitude by GPs, then the so-called input parameters, you can get the current location of the weather. In the simulator, you can perform a simulation by pre-configuring the latitude and longitude. Open the emulator first, and then in the Eclipse menu window, open Perspective-DDMS, enter the configuration to set the desired latitude and longitude in the control Panel. As shown in the image on the right.

Locate the service and learn later.

Need to be aware

If you are using the SSL protocol, HttpClient does not support it. This is primarily due to the need to decide how to handle SSL certificates, whether to accept all certificates, including private or expired, or whether users need to be prompted.

Simple httpclient in the absence of savings as single-threaded use. If multiple threads are required, you can set HttpClient to support multithreading.

Androidhttpclient

Starting with Android2.2 (API level 8), you can use the Androidhttpclient class, which is an implementation of the HttpClient interface in Android.net.http, as in the example Defaulthttpclient. With this class, SSL management can be done by using the static method newinstance to directly fill in the UserAgent (report in your HTTP requests) and obtain an instance of Androidhttpclient. You can increase the date information in the HTTP header to support gzip-compressed content.

Unlike traditional defaulthttpclient, Androidhttpclient does not automatically save cookies and can be processed by HttpContext objects.

In addition, Androidhttpclient does not allow the main thread to be used, only running in a background thread. This requires special attention.

RELATED links: My Andriod development related articles

Android Learning Note (four or five): Internet communication-httpclient, XML parsing (web)

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.