基于xml类型的压缩数据流的android获取天气的方法
16lz
2021-01-23
在制作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(); }}
网上也提供了一些基于非压缩数据流的方法,在这里就不再提及。写此博客也是为了提醒有压缩数据流的存在。
更多相关文章
- 【转】Android -- 探究Android的多分辨率支持以及各种类型图标尺
- 利用gson处理Java反射TypeToken泛型运行时类型擦除
- JAVA如何判断对象的类型
- android 酷欧天气完整项目
- 系统关闭GPRS数据流量和 GPS的方法
- Intent打开各种类型的文件
- 设置里首选网络类型由3G改成4G
- android sqlite 自增数据类型