开发环境android4.0.3
网上有很多android获取天气预报的方法,但是由于android版本更新,在主线程在禁止访问网络权限,因此需要创建一个新的线程连接WebService。
android的WebService 应用soap简单对象协议,这里采用ksoap2-android-assembly-2.5.4-jar-with-dependencies.jar开发包。
连接WebService主要接口如下:
public static SoapObject common(String methodName, HashMap<String, Object>map,
String nameSpace, String endPoint)
{
String soapAction = nameSpace + methodName; //指定WebService的命名空间和调用的方法名
SoapObject rpc = new SoapObject(nameSpace,methodName ); //设置调用WebService就接口需要传入的参数
if (null != map && map.size() > 0)
{
Iterator<Entry<String, Object>> iter = map.entrySet().iterator();
while (iter.hasNext()) {
@SuppressWarnings("rawtypes")
Map.Entry entry = (Map.Entry) iter.next();
Object key = entry.getKey();
Object val = entry.getValue();
rpc.addProperty(key.toString(), val.toString());
}
}
else
{
return null;
}
//生成调用WebService方法的SOAP 请求信息,并制定soap的版本
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER10);
envelope.bodyOut = rpc;
//设置是否调用的doNet开发的WebService
envelope.dotNet = true;
envelope.setOutputSoapObject(rpc);
//设置连接超时时间为20秒
HttpTransportSE transport = new HttpTransportSE(endPoint, timeout);
try{ //调用WebService
transport.call(soapAction, envelope);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
//return "Error:调用web services出错!"+e.getMessage();
}
//获取返回的数据
SoapObject soapObject = null;
try {
soapObject = (SoapObject) envelope.getResponse();
} catch (SoapFault e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
System.out.println("soap" + soapObject.toString());
return soapObject;
}
解析WebService返回的XML的天气预报内容
private String parseWeather(SoapObject detail)
{
String date = detail.getProperty(6).toString();
if (date.isEmpty())
{
return "false";
}
String weatherToday = "今天:" + date.split(" ")[0];
weatherToday = weatherToday + "\n天气:" + date.split(" ")[1];
weatherToday = weatherToday + "\n气温:"
+ detail.getProperty(5).toString();
weatherToday = weatherToday + "\n风力:"
+ detail.getProperty(7).toString() + "\n";
System.out.println("weatherToday is " + weatherToday);
return weatherToday;
}
获取天气预报的方法
public void getWeather(String cityName) { HashMap<String, Object> map = new HashMap<String, Object>(); map.put("theCityName", cityName); SoapObject Result = common( METHOD_NAME,map, NAMESPACE, URL); String ret = parseWeather(Result); Message msg = new Message(); msg.what = this.MESSAGE_WEATHER; Bundle bundle = new Bundle(); bundle.putString("weatherdata", ret); msg.setData(bundle); mHandler.sendMessage(msg); }
下面有整个工程的源代码myWeather