在安卓中获取一个城市的天气情况

在Android应用中获取城市天气信息需要借助第三方API。本文介绍了如何引入ksoap2-android-assembly-2.5.7-jar-with-dependencies.jar库,并提供了一段使用KSOAP2与Web服务交互的代码示例,通过调用特定方法获取并解析天气数据。
摘要由CSDN通过智能技术生成

要在一个安卓应用中获取一个城市的天气需要第三方的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;
   }
}

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值