zoukankan      html  css  js  c++  java
  • XMl解析之Pull解析

    HttpUtils:

    package cn.qf.parser;
    
    
    import java.io.BufferedOutputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    
    import org.apache.http.HttpEntity;
    import org.apache.http.HttpResponse;
    import org.apache.http.ParseException;
    import org.apache.http.client.ClientProtocolException;
    import org.apache.http.client.HttpClient;
    import org.apache.http.client.methods.HttpGet;
    import org.apache.http.impl.client.DefaultHttpClient;
    import org.apache.http.util.EntityUtils;
    
    /**
     * HttpClient请求网络 获取XML数据
     * 
     * @author my
     *
     */
    public class HttpUtils {
        /**
         * Http请求网络获取xml数据
         * 下载图片
         * @param path
         */
        public static void downLoadImg(String path) {
            BufferedOutputStream bos = null;
            try {
                // 1.创建HttpCLient对象
                HttpClient httpClient = new DefaultHttpClient();
                // 2.创建请求对象 指定地址
                HttpGet htpGet = new HttpGet(path);
                // 3.执行请求 获得HttpResponse对象
                HttpResponse response = httpClient.execute(htpGet);
                // 4.获得响应码
                int code = response.getStatusLine().getStatusCode();
                if (code == 200) {
                    // 获得响应的HttpEntity对象
                    HttpEntity entity = response.getEntity();
                    String name = path.substring(path.lastIndexOf("/") + 1);
                    bos = new BufferedOutputStream(new FileOutputStream(name));
                    bos.write(EntityUtils.toByteArray(entity));
                    bos.flush();
                }
            } catch (ClientProtocolException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } finally {
                if (bos != null) {
                    try {
                        bos.close();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }
        }
        /**
         * 从网络下载Xml文件
         * @param path
         * @return
         */
        public static String getXMLByInternet(String path) {
            try {
                // 1.创建httpClient对象
                HttpClient httpClient = new DefaultHttpClient();
                // 2.创建请求对象 指定地址
                HttpGet httpGet = new HttpGet(path);
                // 3.执行请求,获得HttpResponse对象
                HttpResponse response = httpClient.execute(httpGet);
                // 4.获得响应码
                int code = response.getStatusLine().getStatusCode();
                if (code == 200) {
                    // 获得响应的httpEntity对象__客户端服务端传递的载体
                    HttpEntity entity = response.getEntity();
                    return EntityUtils.toString(entity, "GBK");
                }
            } catch (ClientProtocolException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (ParseException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
    
            return null;
        }
    }

    ParserDemo.java

    package com.qf.PullParser4;
    
    import java.io.IOException;
    import java.io.StringReader;
    import java.util.ArrayList;
    import java.util.List;
    
    import org.xmlpull.v1.XmlPullParser;
    import org.xmlpull.v1.XmlPullParserException;
    import org.xmlpull.v1.XmlPullParserFactory;
    
    /**
     * http://api.map.baidu.com/telematics/v3/weather?location=北京&output=xml&ak=
     * mXBIDrvTOwwmYaTtN03Lo0j2 请求上述接口,使用pull解析<date>字段和<dayPictureUrl>字段,并把
     * <dayPictureUrl>字段对应的图片下载到本地, 展示到jsp页面
     * 
     * @author my
     *
     */
    class WeatherDate {
        private String date;
        private String dayPictureUrl;
    
        public String getdate() {
            return date;
        }
    
        public void setdate(String date) {
            this.date = date;
        }
    
        public String getDayPictureUrl() {
            return dayPictureUrl;
        }
    
        public void setDayPictureUrl(String dayPictureUrl) {
            this.dayPictureUrl = dayPictureUrl;
        }
    
        @Override
        public String toString() {
            return "WeatherDate [date=" + date + ", dayPictureUrl=" + dayPictureUrl + "]";
        }
    
    }
    
    public class parserDemo {
        public static void main(String[] args) {
            String xml = HttpUtils.getXMLByInternet(
                    "http://api.map.baidu.com/telematics/v3/weather?location=北京&output=xml&ak=mXBIDrvTOwwmYaTtN03Lo0j2");
            System.out.println(xml);
            try {
                // 创建解析器工厂对象
                XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
                // 创建解析器
                XmlPullParser parser = factory.newPullParser();
                // 设置数据源,
           //StringReader 是Reader的子类
           // StringReader 的数据源是String类型的字符串
             parser.setInput(new StringReader(xml));
                // 得到响应码
                int code = parser.getEventType();
                WeatherDate weatherDate = null;
                List<WeatherDate> list = null;
                String temp = "";
                while (code != XmlPullParser.END_DOCUMENT) {
                    String name = parser.getName();
                    switch (code) {
                    case XmlPullParser.START_TAG:
                        if ("weather_data".equals(name)) {
                            list = new ArrayList<>();
                            temp = "weather";
                        } else if ("date".equals(name) && "weather".equals(temp)) {
                            weatherDate = new WeatherDate();
                            weatherDate.setdate(parser.nextText());
                        } else if ("dayPictureUrl".equals(name)) {
                            String path = parser.nextText();
                            weatherDate.setDayPictureUrl(path);
                            list.add(weatherDate);
                            // 下载图片
                            HttpUtils.downLoadImg(path);
                        }
                        break;
                    default:
                        break;
                    }
                    code = parser.next();
                }
                for (WeatherDate weatherDate2 : list) {
                    System.out.println(weatherDate2);
                }
    
            } catch (XmlPullParserException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
    
        }
    }
  • 相关阅读:
    Stop介绍
    django建站基本步骤
    Js 数组排序函数sort()
    前端面试基础-html篇之CSS3新特性
    前端面试基础-html篇之H5新特性
    2018年前端程序猿最好用的编辑器:visual studio code 常见配置
    适合手机端页面的轮播图,无插件,支持自动循环,一套轮播图可以适应所有的屏幕
    纯css3实现圆点围绕圆圈匀速无限旋转
    xpath 踩坑笔记01 通过a 文本内容标签定位元素
    python3学习记录3
  • 原文地址:https://www.cnblogs.com/fangg/p/5723026.html
Copyright © 2011-2022 走看看