在制作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();    }}

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

更多相关文章

  1. 【转】Android -- 探究Android的多分辨率支持以及各种类型图标尺
  2. 利用gson处理Java反射TypeToken泛型运行时类型擦除
  3. JAVA如何判断对象的类型
  4. android 酷欧天气完整项目
  5. 系统关闭GPRS数据流量和 GPS的方法
  6. Intent打开各种类型的文件
  7. 设置里首选网络类型由3G改成4G
  8. android sqlite 自增数据类型

随机推荐

  1. 2021年北京高新技术企业认定条件及时间
  2. 使用频率最高的21条Linux命令,让你多出一
  3. 《都挺好》弹幕比剧还精彩?394452条弹幕数
  4. 北京高新技术企业认定最新条件及相关要求
  5. 淘宝爬虫实战(附代码和数据集)——今天你防
  6. 测试 python的魔术方法大全!记得收藏!!!
  7. 数据分析实战——EXCEL实现复购率计算
  8. Mac下通过VMware Fusion安装centos虚拟机
  9. for循环
  10. SweynTooth漏洞影响上百蓝牙产品