下面我介绍比较简单的两种方式来完成在Android中调用天气预报。

1.

Weather weather = new Weather();String urlStr = "http://flash.weather.com.cn/wmaps/xml/"+cityId+".xml";try {    url = new URL(urlStr);    urlConnection = (HttpURLConnection)url.openConnection();    InputStream is = urlConnection.getInputStream();    parser = Xml.newPullParser();    parser.setInput(is,"UTF-8");    while(parser.getEventType()!=XmlPullParser.END_DOCUMENT){        if(parser.getEventType() == XmlPullParser.START_TAG){            String name = parser.getName();            if("city".equals(name)){                String cn = parser.getAttributeValue(2);                if(cn.contains(cityName)){                    String weatherStr = parser.getAttributeValue(8);                    weather.setWeather(weatherStr);                }            }        }        parser.next();    }} catch (IOException e) {    e.printStackTrace();} catch (XmlPullParserException e) {    e.printStackTrace();}
2.
Weather[] weather = new Weather[4];//定义取三天的天气//http://m.weather.com.cn/data/101070101.html//String URL = "http://m.weather.com.cn/data/"+CityId+".html";//http://m.weather.com.cn/atad/101070101.htmlString URL="http://m.weather.com.cn/atad/"+cityId+".html";String Weather_Result="";HttpGet httpRequest = new HttpGet(URL);try {    HttpClient httpClient = new DefaultHttpClient();    HttpResponse httpResponse = httpClient.execute(httpRequest);    if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {        Weather_Result = EntityUtils.toString(httpResponse.getEntity());    }} catch (Exception e) {    return weather;}if(null!=Weather_Result&&!"".equals(Weather_Result)){    try {        JSONObject JO = new JSONObject(Weather_Result).getJSONObject("weatherinfo");        for (int i = 0; i < weather.length; i++) {            weather[i] = new Weather();            weather[i].setCityName(JO.getString("city"));            weather[i].setCurrentDate("date_y");            weather[i].setWeek(JO.getString("week"));            weather[i].setTemp(JO.getString("temp"+(i+1)));            weather[i].setWind(JO.getString("wind"+(i+1)));            weather[i].setWeather(JO.getString("weather"+(i+1)));        }    } catch (JSONException e) {        weather = new Weather[4];        return weather;    }}


更多相关文章

  1. Android的自定义长按
  2. Android之TabHost重定义
  3. 自定义圆角button上下间距问题
  4. Android Wifi模块相关常量定义.
  5. Android 自定义ProgressBar--进度自己设置图片
  6. Android_自定义View拖拽重绘
  7. android 自定义具有反弹效果的ScrollView
  8. android自定义对话框工具类

随机推荐

  1. Android图片处理(Matrix,ColorMatrix) -
  2. Android(安卓)EditText 下换线颜色变换
  3. Android(安卓)对手机网络的检测和监听
  4. Android应用开发学习笔记之绘图
  5. Android(安卓)设计模式之桥接模式
  6. Android(安卓)IntentService详解
  7. android 数据存储的四种方式.
  8. Android(安卓)kotlin DataBinding 之 unr
  9. android input 命令总结
  10. Android.mk文件语法规范