雅虎 — 英文天气的API 解析"/>
关于雅虎 — 英文天气的API 解析
官方提供api地址:
.html
本例提供解析代码。api数据格式以上地址可查看。
public void paserxml() throws UnsupportedEncodingException {String cityCode = getCityCode("shenzhen");String str = "="+cityCode+"&u=c";try { domfac = DocumentBuilderFactory.newInstance();dombuilder = domfac.newDocumentBuilder();// NodeList channels;URL ur = new URL(str);HttpURLConnection urlConnection = (HttpURLConnection) ur.openConnection();//打开一个连接 int code1 =urlConnection.getResponseCode();Log.e("liyongjun", "code = "+code1);doc = dombuilder.parse(urlConnection.getInputStream());root = doc.getDocumentElement(); //rss//channels = root.getChildNodes(); //channelsNodeList list = doc.getElementsByTagName("yweather:forecast");int size = list.getLength();for(int i = 0; i<(list.getLength());i++) {//遍历每一个元素Element elt = (Element) list.item(i);String date = elt.getAttribute("date");String day = elt.getAttribute("day");String text = elt.getAttribute("text");String low = elt.getAttribute("low");String high = elt.getAttribute("high");}} catch (MalformedURLException e) {e.printStackTrace();} catch (IOException e) {Log.e("liyongjun", "网络连接超时!");} catch (ParserConfigurationException e) {e.printStackTrace();} catch (SAXException e) {e.printStackTrace();}}
获得城市代码(yahoo提供)
public String getCityCode(String name) throws UnsupportedEncodingException{String code = null;String paramString="=select*from%20geo.places%20where%20text=%27"+name+"%27";try { domfac = DocumentBuilderFactory.newInstance();dombuilder = domfac.newDocumentBuilder();NodeList results;URL url = new URL(paramString);HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();//打开一个连接 doc = dombuilder.parse(urlConnection.getInputStream());root = doc.getDocumentElement();results = root.getChildNodes(); //resultsif(results.getLength() > 0){Node node = results.item(0).getFirstChild(); //得到 item 第一个 placeNodeList places = node.getChildNodes(); //得到place下所有子节点code = places.item(0).getFirstChild().getNodeValue(); //指向第一个place,拿到第一个子节点 wodid 获得value}} catch (MalformedURLException e) {e.printStackTrace();} catch (SAXException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} catch (ParserConfigurationException e) {e.printStackTrace();}return code;}
查询城市ID API
=select*from geo.places where text= ' "+name+" ' ";
name:即需要的查询城市的英文名。
更多推荐
关于雅虎 — 英文天气的API 解析
发布评论