Android Study Notes (four or five): Internet communication-httpclient, XML parsing (W3C)

Source: Internet
Author: User
Tags xml parser

Android 4.0 icecream was released a few days ago. It was found on the internet yesterday that the begining book had the version of Edition 3. For comparison, there are still some changes, not only the tablet part, there are some revisions and adjustments to the original chapters. Read Edtion 3 in the order of Edtion 2, read Edtion 3 in the same chapter, and then look back at chapter of Edition 3.
24, 25 (36 of E2), 26, 27, 28, 29, 44, 45, 46, and 47. At the same time, the simulator is changed to Android 2.3, which has been adapted to possible new changes.

Accessing the Internet is an important user of a device. I have learned how to embed WebKit before. In addition, we can access intenet through APIS. Android provides the Apache httpclient library. Based on this, other protocols can be considered as HTTP encapsulated formats, such as XML and JSON. You can obtain the details of the HTTP client at http://hc.apache.org.

Android provides three XML Parser: 1. The traditional W3C Dom Parser (Org. w3C. dom); 2. the SAX Parser (Org. XML. SAX); 3. Previous Android Study Notes (38): xmlpullparser is used in resource (I. In addition, the JSON Parser (Org. JSON) is provided ). You can also use a third-party parser.
The implementation steps are as follows:

  1. You can use DefaultHttpClient to create the HttpClient interface object.
  2. The request and HttpRequest are customized, including HttpGet and HttpPost. However, you can execute the request through execute.
  3. You can use the HttpResponsed object to process the returned results, with response code (such as 200, that is, 200 OK), Http header, and ResponseHandler in execute () as the parameter. The response body will be returned here, however, this method is feasible but not recommended, because we should usually response code.

The following is a small example of a weather widget. httpclient is used to send a request to a URL (Google's weather Query Web page) using the httpget tool. The weather information in XML format is returned for analysis, and the results are processed through the WebKit browser. The following shows the response to the weather in Guangzhou. In this example, the first step is to learn httpclient usage, and the second step is to learn XML parsing. This time, the W3C Dom parser is used for analysis through nodelist and element.


<Xml_api_reply version = "1">
<Weather module_id = "0" tab_id = "0" mobile_row = "0" mobile_zipped = "1" row = "0" section = "0">
<Forecast_information><! -- Query the location information. Only the part for analysis is provided. -->
... ...
<Postal_code data = "Guangzhou"/>
<Forecast_date data = "2011-10-27"/>
</Forecast_information>
<Current_conditions><! -- Show the current weather conditions and only the part for analysis -->
<Condition data = "partial Cloudy"/>
<Temp_c data = "27"/>
<Humidity data = "humidity: 48%" type = "humidity" text = "humidity"/>
<Icon data = "/ig/images/weather/partly_cloudy.gif"/>
<Wind_condition data = "wind direction: north, wind speed: 2 meters/second"/>
</Current_conditions>
<Forecast_conditions><! -- Give the weather forecast for the day -->
<Day_of_week DATA = "Thursday"/>
<Low data = "21"/>
<High data = "28"/>
<Icon DATA = "/IG/images/weather/mostly_sunny.gif"/>
<Condition data = "mainly Sunny"/>
</Forecast_conditions>
<Forecast_conditions><! -- Weather forecast for tomorrow -->
......
</Forecast_conditions>
<Forecast_conditions><! -- Give the weather forecast for the day after tomorrow -->
... ...
</Forecast_conditions>
<Forecast_conditions><! -- Give the weather forecast for the third day -->
... ...
</Forecast_conditions>
</Weather>
</Xml_api_reply>

The program code is as follows:

(This interface is a private interface of igoogle and has been disabled. 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; // content displayed in the webview Layout
PrivateHttpClientClient = NULL;
Private list <forecast> forecasts = new arraylist <forecast> ();
// Use list to save the weather conditions in the next few days
Private currentweather currentcondition = NULL;
// Save the real-time weather conditions and location time
Private string format = "http://www.google.com/ig/api? Hl = ZH-CN & weather = % 1 s "; // API for querying 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 an object for the HttpClient interface, which can be created through DefaultHttpClient.
Client = new DefaultHttpClient ();
}

Protected void onResume (){
Super. onResume ();
UpdateForecast ("Guangzhou"); // Step 2. Request the weather information of Guangzhou from the Internet to obtain and present the information.
}

Protected void onDestroy (){
Super. onDestroy ();
// Step 3: Release the httpclient resources. This step is not tracked in detail. If it is estimated that no response is received after the connection is established, the connection is terminated during activity destroy.
Client. getconnectionmanager (). Shutdown ();
}

// Step 2. Request weather information of Guangzhou from the Internet to obtain and present the information
Private void updateforecast (string citycode ){
String url = string. Format (format, citycode );
// Step 2.1: generate an httpget request and send it to the Internet through execute (). Then, return the 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 obtain the weather information from the response
String page = generatepage (); // Step 2.3 is rendered in WebKit browser through HTML
Browser.LoadDataWithBaseURL(Null, page, "text/html", "UTF-8", null );
} Catch (throwable t ){
Toast. maketext (this, "request failed:" + T. tostring (), 5000). Show ();
}
}
// Step 2.2 obtain the weather information from the returned result. Note the format with throws exception.
Private void buildforecasts (string raw)Throws Exception{
DocumentBuilder builder = DocumentBuilderFactory. newInstance (). newDocumentBuilder ();
Document doc = builder. parse (new InputSource (new StringReader (raw )));
// Obtain real-time weather information, location information, and time information. The method is the same as that used to obtain future weather forecasts. The information is skipped and stored in currentCondition.
.... ....

// For XML <node_name node_attribute = attribute_valule> node_vaule </node_name>
NodeList furCondition = doc.GetElementsByTagName("Forecast_conditions ");
// Obtain the weather forecast for the next four days.
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 describes how to read the required information from each element group. In addition, if you prefer node, such as E. getfirstclide () can be obtained or node. getattributes (). getnameditem ("data "). getnodevalue () to get the carried property value
Private string getweatherattribute (Element E, string name ){
Nodelist T = E.GetElementsByTagName(Name );
Element A = (element) T. Item (0 );
Return.GetAttribute("Data ");
}

// Step 2.3 display in webkit browser through HTML
Private String generatePage (){
StringBuilderBufResult = new StringBuilder ("BufResult.Append("<H2> <font color = \" red \ ">" + currentCondition. getCity () + "</font> ... ... // Display real-time information
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 the weather forecast information and provide the get Method */.....
}
Private class currentweather {
.... /* Store the current weather, time, and location, and provide the get Method */....
}
}

Obtain local weather information by latitude and longitude

In Google's weather forecast API, you can also enter latitude and longitude, format: http://www.google.com/ig/api? Hl = ZH-CN & weather =, 23080000,113170000, which is the longitude and latitude of Guangzhou. Android can obtain the longitude and latitude through GPS, and then input parameters to obtain the weather in the current location. In the simulator, you can configure the longitude and latitude in advance for a simulation. Open the simulator first, and then go to the eclipse menu window-> open perspective
-> Ddms: Enter the configuration. You can set the required longitude and latitude in the control panel. As shown in the right figure.

Locate the service and study again.

Note:

Httpclient does not support SSL protocol. This is mainly because you need to decide how to handle SSL certificates, whether to accept all certificates, including private or expired certificates, or whether to notify users.

Simple httpclient is used as a single thread by default. If multithreading is required, you can set httpclient to support multithreading.

AndroidHttpClient

From Android2.2 (API level 8), you can use the AndroidHttpClient class. In android.net. http, it is an implementation of the HttpClient interface, just like DefaultHttpClient In the example. This class enables SSL management. You can use the static method newInstance to directly enter the userAgent (report in your HTTP requests) and obtain the AndroidHttpClient instance. You can add date information in the HTTP header, supports gzip compressed content.

Unlike the traditional DefaultHttpClient, AndroidHttpClient does not automatically save cookies and can be processed through the HttpContext object.

In addition, AndroidHttpClient cannot be used by the main thread and can only run in the background thread. Pay special attention to this.

Related Links: My Andriod development articles

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.