要在一个安卓应用中获取一个城市的天气需要第三方的api,从网上下载ksoap2-android-assembly-2.5.7-jar-with-dependencies.jar包,然后再工程中新建一个lib文件夹,将下载的jar包放入该文件夹下,并在工程Build Path>Configure Build Path…>libraries 中选择“Add Externel JARs…”,选定ksoap2-android-assembly-2.5.7-jar-with-dependencies.jar,点击OK,这样就可以将ksoap2-android-assembly-2.5.7-jar-with-dependencies.jar库文件引入。然后在工程Build Path>Configure Build Path…>Order and Export 中将引入的库文件ksoap2-android-assembly-2.5.7-jar-with-dependencies.jar 选中。
然后主要代码如下:
package weather.standopen;
import java.io.UnsupportedEncodingException;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import android.widget.Toast;
public class Weather {
private static final String NAMESPACE = "http://WebXml.com.cn/";
private static String URL = "http://www.webxml.com.cn/webservices/weatherwebservice.asmx";
private static final String METHOD_NAME = "getWeatherbyCityName";
private static String SOAP_ACTION = "http://WebXml.com.cn/getWeatherbyCityName";
private String weatherToday;
private SoapObject detail;
public String GetCityMessage(String CityName)//更具所给的城市名获取该城市的天气情况。
{
String message=null;
try{
SoapObject rpc = new SoapObject(NAMESPACE, METHOD_NAME);
rpc.addProperty("theCityName", CityName);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.bodyOut = rpc;
envelope.dotNet = true;
envelope.setOutputSoapObject(rpc);
HttpTransportSE ht = new HttpTransportSE(URL);
ht.debug = true;
ht.call(SOAP_ACTION, envelope);
detail =(SoapObject) envelope.getResponse();
message=detail.toString();
}catch(Exception e){
e.printStackTrace();
}
return message;
}
public String GetWeather() throws UnsupportedEncodingException
{
//解析或得的信息得到天气信息,在该函数中药用到detail
//detail是定义的全局变量,但需要先调用 GetCityMessage函数
String date = detail.getProperty(6).toString();
weatherToday = weatherToday + "\n天气:" + date.split(" ")[1];
weatherToday = weatherToday + "\n气温:"+ detail.getProperty(5).toString();
weatherToday = weatherToday + "\n风力:"+ detail.getProperty(7).toString() ;
return weatherToday;
}
}