Android网络编程之Web Service获取天气预报( 获取天气预报信息)
上一篇完成了本应用第一步:下拉列表填充省市信息,本篇完成获取天气预报信息部分:
Activity中的Spinner监听事件:
View Code
private class CityChoosedListener implements OnItemSelectedListener { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { // 调用工具类的getWeatherMsgByCity静态方法,返回解析后的String字符串 String weatherMsg = WebServiceUtil.getWeatherMsgByCity(MainActivity.this.citySpinner.getItemAtPosition(position).toString()); MainActivity.this.weatherInfoText.setText(weatherMsg); } @Override public void onNothingSelected(AdapterView<?> arg0) { } } }
工具类中的getWeatherMsgByCity()方法通过Post方式获取天气信息:
Post方式详情可见:http://www.cnblogs.com/moka/archive/2013/05/05/3060765.html
View Code
/* 使用Post方式根据城市名获取天气数据 */ public static String getWeatherMsgByCity(String cityName) { String result = ""; String url = "http://webservice.webxml.com.cn/WebServices/WeatherWS.asmx/getWeather"; HttpPost request = new HttpPost(url); List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("theCityCode", cityName)); params.add(new BasicNameValuePair("theUserID", "")); try { request.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8)); HttpResponse response = new DefaultHttpClient().execute(request); // 检测回应状态码 if (response.getStatusLine().getStatusCode() == 200) { String temp = EntityUtils.toString(response.getEntity()); // 返回数据均为XML格式,要根据具体格式从中提取出所需字符串 result = parseWeatherInfo(temp); } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return result; }
解析方法与上一篇大同小异,直接提取Xml中的有效文字信息:
View Code
/*解析传回的天气信息xml文件*/ private static String parseWeatherInfo(String temp) { String result = ""; String[] results = null; StringBuffer buffer = new StringBuffer(); if (temp != null && temp.length() > 0) { int start = temp.indexOf("<string>"); int end = temp.lastIndexOf("</ArrayOfString>"); result = temp.substring(start, end); results = result.split("</string>"); for (int i = 1; i < results.length - 1; i++) { // 因为解析时最后会在String数组中多一项长度为二的空白字符,所以i < results.length - 1 buffer.append(results[i].substring(12) + "\n"); } } return buffer.toString(); } }
运行后效果如图: