«

Android中调用天气预报

时间:2024-3-2 19:40     作者:韩俊     分类: Android


下面我介绍比较简单的两种方式来完成在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.html
String 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;
    }
}



        <p>版权声明:本文为博主原创文章,未经博主允许不得转载。</p>

标签: android

热门推荐