首先,我的app需要通过网络来获取当前所在的位置。这里我找到了一个json来获取本地位置信息。
http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=js //获得当前网络所在城市
返回来的信息是:
var remote_ip_info = {"ret":1,"start":-1,"end":-1,"country":"\u4e2d\u56fd","province":"\u6cb3\u5357","city":"\u6d1b\u9633","district":"","isp":"","type":"","desc":""};
返回信息中的汉字编码是gbk,这里我们需要转一下编码就能直接拿到位置信息。
country 是 国家,province 是 省份,city 是所在的城市。这里我就可以通过网络来获取我当前所在的位置信息。
在网上查了一下,查询天气预报都是通过查询服务器上的json来获取天气信息。
http://wthrcdn.etouch.cn/WeatherApi?city=北京 //获得北京近几天的天气情况 http://www.weather.com.cn/data/cityinfo/101010100.html //101010100北京的气象ID
这是贴除了两个网址,第一个返回是xml格式,需要通过xml解析。第一个返回的信息较全,但是第二个好像也有较全的信息,但是我通过网上的链接一直是返回失败。
第一个有一个缺点,就是没有当天的天气状态(晴、多云、雨等),但是对预报来说却有。
第二个温度信息不怎么准。没有弄明白是怎么回事。
获取json需要通过http协议,这里贴上我用到到的代码:(传入json地址,直接返回字符串)
package com.lmissw.mydesignedapp; import com.lmissw.mydesignedapp.MainActivity; import android.util.Log; import android.widget.Toast; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.ProtocolException; import java.net.URL; /** * Created by ZhouWangsheng on 2018/1/9. */ public class httpGetString { private static String urlString = null; private static String httpUrl = null; private InputStream outStream = null; private static String outString = null; public static String getString( String urlStr ) { if(urlStr==null) return null; urlString=urlStr; outString = null; Thread httpThread = new Thread(new Runnable() { @Override public void run() { HttpURLConnection connection = null; try { URL url = new URL(urlString); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Charset", "UTF-8"); // 设置字符集 connection.setConnectTimeout(8000); connection.setReadTimeout(8000); int code = connection.getResponseCode(); if (code == 200) { InputStream outStream = connection.getInputStream(); int fileLength = connection.getContentLength(); BufferedReader reader = new BufferedReader(new InputStreamReader(outStream)); StringBuilder jsonText = new StringBuilder(); String line = null; try { while ((line = reader.readLine()) != null) { jsonText.append(line + "/n"); } } catch (IOException e) { e.printStackTrace(); } finally { try { outStream.close(); } catch (IOException e) { e.printStackTrace(); } outString = jsonText.toString(); } Log.i("Infor", "请求成功 "+fileLength); } else { Log.i("Infor", "请求失败"); } } catch (ProtocolException e) { e.printStackTrace(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (connection != null) { connection.disconnect(); Log.i("Infor", "disconnect ok"); } } } }); httpThread.start(); while(httpThread.isAlive()); Log.i("Infor", "httpData:"+outString); return outString; } }
下面是解析天气信息的json:
private void analysisJsonWeather( String jsonString ) { try { JSONTokener jsonParser = new JSONTokener( jsonString ); JSONObject json = (JSONObject)jsonParser.nextValue(); JSONObject jsonWeather = json.getJSONObject("weatherinfo"); String str = jsonWeather.getString("city"); if(str.equals(localCity)==false) { return; } str = jsonWeather.getString("temp1"); // today.temperMin= Integer.parseInt(str.replaceAll("[^-+.\\d]", "")); str = jsonWeather.getString("temp2"); // today.temperMax= Integer.parseInt(str.replaceAll("[^-+.\\d]", "")); // Log.i("Infor", "max min:"+today.temperMax+" "+today.temperMin); today.type = jsonWeather.getString("weather"); // Log.i("Infor", "type:"+today.type); } catch (JSONException e) { e.printStackTrace(); } }
最后附上解析xml的代码:
//通过网络获取天气信息的xml文件 String xmlText = httpGetString.getString(httpWeather+localCity); if(xmlText==null) return false; String str=" "; ByteArrayInputStream stream = new ByteArrayInputStream(xmlText.getBytes()); try { XmlPullParserFactory pullFactory=XmlPullParserFactory.newInstance(); XmlPullParser pullParser=pullFactory.newPullParser(); pullParser.setInput(stream,"UTF-8"); int entype=pullParser.getEventType(); while (entype!=XmlPullParser.END_DOCUMENT) { String startTag=null; String textData=null; switch(entype) { case XmlPullParser.START_DOCUMENT: break; case XmlPullParser.START_TAG: String name = pullParser.getName(); if (name.equalsIgnoreCase("city")) { String xmlCity = pullParser.nextText(); if (xmlCity.equalsIgnoreCase(localCity) == false) // 如果后面是Text元素,即返回它的值 { Log.i("Infor", "获取城市天气出错,当前获取的城市是:" + xmlCity); return false; } } else if (name.equalsIgnoreCase("wendu")) { today.temper = Integer.parseInt(pullParser.nextText()); } else if (name.equalsIgnoreCase("shidu")) { /* 删除非数字部分 */ String num = pullParser.nextText().replaceAll("[^-+.\\d]", ""); today.humidity = Integer.parseInt(num); } else if (name.equalsIgnoreCase("fengxiang")) { today.windDir = pullParser.nextText(); } else if (name.equalsIgnoreCase("updatetime")){ today.updateTime = pullParser.nextText(); }else if (name.equalsIgnoreCase("yesterday")) { int begin = xmlText.toString().indexOf(‘!‘); String fengliString = xmlText.substring(begin+6,begin+16); begin = fengliString.toString().indexOf(‘[‘); int end = fengliString.toString().indexOf(‘]‘); today.windpower = fengliString.substring(begin+1,end); Log.i("Infor", "风力:" + today.windpower); return true; } break; case XmlPullParser.END_DOCUMENT: break; case XmlPullParser.END_TAG: pullParser.getName(); break; } entype=pullParser.next(); } } catch (Exception e) { e.printStackTrace(); } try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } Log.i("Infor", "获得当前位置:"+str);