Android学习笔记(四五):互联网通讯-HttpClient、XML解析(W3C)

前几日Android发布了4.0 Icecream,昨天上网发现Begining Book中有Edition 3的版本,比对一下,仍是有至关的改动,不只仅增长了tablet的部分,对原有的章节有有一些修订,先后的调整等等。先按Edtion 2的顺序看,相同章节的看Edtion 3,而后回头看Edition 3的Chapter 2四、25(E2的36)、2六、2七、2八、2九、4四、4五、4六、47几个新增章节。同时将模拟器改成Android 2.3的版本,已适应可能新增的改动。html

访问Internet是设备的一个重要用户,以前学习过如何嵌入Webkit,此外咱们能够经过API来访问Intenet。Android提供Apache HttpClient库,基于此,其余协议,能够视为在HTTP封装的格式,例如XML,JSON等。HTTP Client的详细资料可在http://hc.apache.org/中获取。node

Android提供三个XML的解析器: 一、传统的W3C DOM parser(org.w3c.dom); 二、SAX解析器(org.xml.sax); 三、以前Android学习笔记(三八):资源resource(上)中使用XmlPullParser。 另外提供JSON解析器(org.json)。固然也可使用第三方的解析器。 实现的步骤以下:android

  1. 建立HttpClient接口的对象,能够经过DefaultHttpClient来建立。
  2. 请求和HttpRequest相帮定,包括HttpGet,HttpPost,然手执行经过execute()来执行请求。
  3. 可使用HttpResponsed对象处理返回,带有response code(例如200,即200 OK),Http头等,另外能够在execute()中携带ResponseHandler做为参数,将在此返回response body,然则此法可行但不推荐,由于一般来说咱们应该response code。

下面是一个天气widget的小例子,采用HttpClient,是以哦那个HttpGet发出对某个URL(google的天气查询网络页面)请求,返回xml格式的天气信息,从中分析,并将结果经过WebKit Browser的方式程序,下面是查找广州天气的返回。在例子中,第一学习HttpClient的用法,第二也学习XML的解析,这次采用W3C DOM解析器,经过NodeList和Element来进行分析。web


<xml_api_reply version="1">  
<weather module_id="0" tab_id="0" mobile_row="0" mobile_zipped="1" row="0" section="0"> 
<forecast_information>  <!-- 查询地点信息,只给出准备分析的部分 -->
    … …  
    <postal_code data="广州"/>  
    <forecast_date data="2011-10-27"/>  
</forecast_information> 
<current_conditions>  <!-- 给出当前的天气状况,只显示准备分析的部分 -->
    <condition data="局部多云"/>  
    <temp_c data="27"/> 
    <humidity data="湿度: 48%"/> 
    <icon data="/ig/images/weather/partly_cloudy.gif"/> 
    <wind_condition data="风向: 北、风速:2 米/秒"/> 
</current_conditions>   
<forecast_conditions>  <!-- 给出当每天气预报 -->
    <day_of_week data="周四"/> 
    <low data="21"/> 
    <high data="28"/> 
    <icon data="/ig/images/weather/mostly_sunny.gif"/> 
    <condition data="以晴为主"/> 
</forecast_conditions> 
<forecast_conditions> <!-- 给出明每天气预报 -->
      ... ... 
</forecast_conditions> 
<forecast_conditions> <!-- 给出后每天气预报 -->
      … … 
</forecast_conditions> 
<forecast_conditions> <!-- 给出第三每天气预报 -->
      … … 
</forecast_conditions> 
</weather> 
</xml_api_reply>apache

程序代码以下:json

(这个接口属于iGoogle的私有接口,已经被关闭,能够找其余的weather api,例如http://www.wunderground.com/weather/api/。 Wei , 2012.9 )api

public class Chapter25Test1 extends Activity{ 
    private WebView browser = null;  //采用WebView来排版显示的内容
    private HttpClient client = null; 
    private List<Forecast> forecasts = new ArrayList<Forecast>();  //采用List来保存将来几天的天气状况 
    private CurrentWeather currentCondition = null;  //保存即时天气状况和地点时间 
    private String format = "http://www.google.com/ig/api?hl=zh-cn&weather=%1s"; //Google XML天气信息的查询API接口
     
    protected void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
        setContentView(R.layout.chapter_25_test1);
        browser = (WebView) findViewById(R.id.c131_webkit);
        //步骤一、建立HttpClient接口的对象,能够经过DefaultHttpClient来建立。
        client = new DefaultHttpClient(); 
    }  

     protected void onResume() {  
        super.onResume(); 
        updateForecast("广州");  //步骤二、向Internet请求广州的天气信息,获取信息,并呈现
    }  

    protected void onDestroy() {  
        super.onDestroy(); 
        //步骤三、释放HttpClient的资源,此步没详细跟踪,按字面估计如一直链接无回复,则在Activity Destroy的时候,终止链接
        client.getConnectionManager().shutdown(); 
    }  

    //步骤二、向Internet请求广州的天气信息,获取信息,并呈现 
    private void updateForecast(String citycode ){ 
        String url = String.format(format, citycode); 
        //步骤2.一、生成HttpGet请求,并经过execute( )向Internet发出,在responseHandler中获得返回值。
        HttpGet getMethod = new HttpGet(url); 
        try{ 
            ResponseHandler<String> responseHandle = new BasicResponseHandler();
            String responseBody = client.execute(getMethod,responseHandle);
            buildForecasts(responseBody);  //步骤2.2 从返回中获取天气信息
            String page = generatePage();   //步骤2.3 经过HTML在webkit browser中呈现
            browser.loadDataWithBaseURL(null, page, "text/html", "UTF-8", null);
        }catch(Throwable t){  
            Toast.makeText(this,"Request failed : "+ t.toString(), 5000).show();
        } 
    } 
    //步骤2.2 从返回中获取天气信息,注意这种带throws Exception的写法
    private void buildForecasts(String raw) throws Exception{    
        DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        Document doc = builder.parse(new InputSource(new StringReader(raw))); 
        //获取即时天气信息和地点、时间信息,方式和后面获取将来天气预报同样,较为繁琐,略过,信息存放在currentCondition中
         …. ….  

        //对于XML<node_name  node_attribute=attribute_valule> node_vaule </node_name> 
        NodeList furCondition = doc.getElementsByTagName("forecast_conditions");
        //有将来四日天气预报,分别取出 
        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); 
    }  
     
    //下面是从每组Element中读取所需信息,另外补充的是若是爱用Node,例如e.getFirstClide()获取,也能够 node.getAttributes().getNamedItem("data").getNodeValue() 来得到携带的属性值
    private String getWeatherAttribute(Element e, String name){ 
        NodeList t = e.getElementsByTagName(name); 
        Element a = (Element)t.item(0); 
        return a.getAttribute("data"); 
    }  

     //步骤2.3 经过HTML在webkit browser中呈现 
    private String generatePage(){ 
        StringBuilder bufResult  = new StringBuilder("<html><body><table width=\"100%\">");
        bufResult.append("<h2><font color=\"red\">" + currentCondition.getCity() + "</font></h2>\n"); 
        … … //显示即时信息
        bufResult.append ("<table><tr><th width=\"25%\">Time</th>"+ 
        "<th width=\"25%\">温度</th><th colspan=\"2\" width=\"50%\">天气状况</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\"><img src=\"http://www.google.com/");
            bufResult.append(forecast.getIcon()); 
            bufResult.append("\"></td></tr>");  
        } 
        bufResult.append("</table></body></html>"); 
        return bufResult.toString(); 
    } 
    private class Forecast{  
         …. /* 存放天气预报信息,并提供get获取方法*/ ….. 
    } 
    private class CurrentWeather{  
       …. /* 存放当前天气、时间、地点,并提供get获取方法*/ …. 
    } 
cookie

经过经纬度获取当地天气网络

在Google的天气预报api中,也是能够输入经纬度,格式为:http://www.google.com/ig/api?hl=zh-cn&weather=,,,23080000,113170000,这是广州的经纬度。Android能够经过GPS获取经纬度,而后所谓输入参数,能够获得当前所在地的天气。在模拟器中,能够经过预先配置经纬度来进行个模拟。先打开模拟器,而后在Eclipse的菜单Window -> Open Perspective -> DDMS,进入配置,可在Control Panel中设置所需的经纬度。如右图所示。多线程

定位服务之后再学习。

须要注意

若是是要使用SSL协议,HttpClient并不支持。主要是由于须要决定如何处理SSL证书,是否接受全部证书,包括私有或者已通过期的正确,或者是否须要提示用户。

简单的HttpClient在缺省下做为单线程使用。若是须要多线程,能够设置HttpClient支持多线程。

AndroidHttpClient

从Android2.2(API level 8)开始,可使用AndroidHttpClient类,在android.net.http中,是HttpClient接口的一个实现,就如例子中的DefaultHttpClient。经过这个类,能够进行SSL管理;可经过静态方法newInstance来直接填写userAgent(report in your HTTP requests)并获取AndroidHttpClient的实例,能够在HTTP头能增长date信息,支持gzip压缩的内容。

和传统的DefaultHttpClient不一样,AndroidHttpClient不会自动保存cookies,可经过HttpContext对象来处理。

此外,AndroidHttpClient不容许主线程使用,只能在后台线程运行。这点须要特别注意。

相关连接:个人Andriod开发相关文章

相关文章
相关标签/搜索