基于xml类型的压缩数据流的android获取天气的方法

来源:互联网 发布:程序员简历 markdown 编辑:程序博客网 时间:2024/06/05 03:47

在制作android天气预报软件的过程中,获取天气资源通常通过一些网站提供的API来获取的,API返回的文件类型可能是xml的,也有可能是json的,传输的数据流一般是正常的。其实,从API的服务器中获取的数据流也有可能是压缩的。那么,接下来,将提供一个基于xml类型的压缩数据流的android获取天气的方法:

public class GetWeather{    static String weather;    static String high;    static String low;    public void getweather()    {        URL url;        try{            DocumentBuilderFactory domFac = DocumentBuilderFactory.newInstance();            DocumentBuilder domBuilder = domFac.newDocumentBuilder();            Document doc;            Element root;            NodeList books;            url = new URL("weatherAPIwebsite");//weatherAPIwebsite是提供服务的url            URLConnection uc = url.openConnection();            uc.setDoOutput(true);            InputStream in = new GZIPInputStream(uc.getInputStream());//解压缩数据流            Reader rd = new InputStreamReader(in,"UTF-8");//UTF-8一般是xml类型的编码类型            int c = 0;            StringBuffer temp = new StringBuffer();            String strHtml;            while ((c = rd.read()) != -1) {                temp.append((char) c);            }            in.close();            strHtml = temp.toString();            System.out.println(strHtml);            doc = domBuilder.parse(new InputSource(new ByteArrayInputStream(strHtml.getBytes("utf-8"))));            root = doc.getDocumentElement();            books = root.getChildNodes();            Node node = doc.getElementsByTagName("wendu").item(0).getFirstChild();            System.out.println(node.getTextContent());        }catch (Exception e)        {            System.out.println("获取天气失败"+e);        }    }    public static void main (String[] args)    {        GetWeather t = new GetWeather();        t.getweather();    }}

网上也提供了一些基于非压缩数据流的方法,在这里就不再提及。写此博客也是为了提醒有压缩数据流的存在。

2 0
原创粉丝点击