调用WEB服务,获取天气预报

From:http://www.cnblogs.com/ghj1976/archive/2011/04/26/2028904.html

1 创建一个新的Adnroid项目

2 获取并使用KSOAP包

比较常用的是KSOAP2 ,用于进行WEB服务的调用

下载地址:http://code.google.com/p/ksoap2-android/ 下载界面如下图

拷贝下载的ksoap2-android-assembly-3.0.0-jar-with-dependencies.jar文件到Eclipse 软件的libs目录下。

选择项目,右键菜单中 Build Path –> Add External Archives… 增加这个下载的包,如下图所示:

在AndroidManifest.xml文件如下:

<?xml version="1.0"   encoding="utf-8"?>

<manifest   xmlns:android="http://schemas.android.com/apk/res/android"

      package="com.example.study2"

      android:versionCode="1"

      android:versionName="1.0" >

      <uses-sdk

          android:minSdkVersion="8"

          android:targetSdkVersion="17" />

      <application

          android:allowBackup="true"

          android:icon="@drawable/ic_launcher"

          android:label="@string/app_name"

          android:theme="@style/AppTheme" >

          <activity

              android:name="com.example.study2.MainActivity"

              android:label="@string/app_name" >

            <intent-filter>

                <action android:name="android.intent.action.MAIN"   />

                <category   android:name="android.intent.category.LAUNCHER" />

            </intent-filter>

          </activity>

      </application>

    <uses-permission   android:name="android.permission.INTERNET"></uses-permission>   

</manifest>

3 activity_main.xml 界面文件内容如下:

 

<RelativeLayout   xmlns:android="http://schemas.android.com/apk/res/android"

      xmlns:tools="http://schemas.android.com/tools"

      android:layout_width="match_parent"

      android:layout_height="match_parent"

      android:paddingBottom="@dimen/activity_vertical_margin"

      android:paddingLeft="@dimen/activity_horizontal_margin"

      android:paddingRight="@dimen/activity_horizontal_margin"

      android:paddingTop="@dimen/activity_vertical_margin"

      tools:context=".MainActivity" >

      <TextView

          android:id="@+id/textView1"

          android:layout_width="wrap_content"

          android:layout_height="wrap_content"

          android:text="@string/hello_world" />

      <Button

          android:id="@+id/btn_Search"

          android:layout_width="100dp"

          android:layout_height="wrap_content"

          android:layout_alignLeft="@+id/textView1"

          android:layout_below="@+id/textView1"

          android:layout_marginLeft="42dp"

          android:text="查询天气预报" />   

</RelativeLayout>

4 MainActivity.java 主程序,代码如下:

import android.os.Bundle;

import android.app.Activity;

import android.view.Menu;

import   java.io.UnsupportedEncodingException;

import android.view.View;

import android.widget.Button;

import android.widget.Toast;

import org.ksoap2.SoapEnvelope;

import   org.ksoap2.serialization.SoapObject;

import   org.ksoap2.serialization.SoapSerializationEnvelope;

//import   org.ksoap2.transport.AndroidHttpTransport;

import   org.ksoap2.transport.HttpTransportSE;

public class MainActivity extends   Activity {

       private   Button okButton;

       //命名空间

       private   static final String NAMESPACE = "http://WebXml.com.cn/";

       //   WebService地址

       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   void getWeather(String cityName) {

              try   {

                     System.out.println("rpc------");

                     SoapObject   rpc = new SoapObject(NAMESPACE, METHOD_NAME);

                     System.out.println("rpc"   + rpc);

                     System.out.println("cityName   is " + cityName);

                     //设置调用参数

                     rpc.addProperty("theCityName",   cityName);

                     //设置SOAP请求信息

                     //SOAP   是一种简单的基于 XML   的协议,它使应用程序通过 HTTP 来交换信息

                     SoapSerializationEnvelope   envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);

                     envelope.bodyOut   = rpc;

                     envelope.dotNet   = true;

                     envelope.setOutputSoapObject(rpc);                  

                     //构建传输对象,

//并指明WSDL文档URL (Web Services Description   Language)

                     HttpTransportSE   ht = new HttpTransportSE(URL);

                     //AndroidHttpTransport   ht = new AndroidHttpTransport(URL);

                     //ht.debug   = true;

            //调用WebService(其中参数为1:命名空间+方法名称,2:Envelope对象)

                     ht.call(SOAP_ACTION,   envelope);

                     //ht.call(null,   envelope);

                     //SoapObject   result = (SoapObject)envelope.bodyIn;

                     //detail   = (SoapObject) result.getProperty("getWeatherbyCityNameResult");

                     detail   =(SoapObject) envelope.getResponse();                  

                     //System.out.println("result"   + result);

                     System.out.println("detail"   + detail);

                     Toast.makeText(this,   detail.toString(), Toast.LENGTH_LONG).show();

                     parseWeather(detail);

                     return;

              }   catch (Exception e) {

                     e.printStackTrace();

              }

       }

       private   void parseWeather(SoapObject detail)

                     throws   UnsupportedEncodingException {

              String   date = detail.getProperty(6).toString();

              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);

              Toast.makeText(this,   weatherToday, Toast.LENGTH_LONG).show();

       }

       @Override

       protected   void onCreate(Bundle savedInstanceState) {

              super.onCreate(savedInstanceState);

              setContentView(R.layout.activity_main);           

              okButton   = (Button) this.findViewById(R.id.btn_Search);

              okButton.setOnClickListener(new   Button.OnClickListener() {

                     @Override

                     public   void onClick(View v) {

                              String city = "苏州";

                              getWeather(city); 

                     }

              });         

              //okButton.setOnClickListener(listener2);

       }

       @Override

       public   boolean onCreateOptionsMenu(Menu menu) {

              //   Inflate the menu; this adds items to the action bar if it is present.

              getMenuInflater().inflate(R.menu.main,   menu);

              return   true;

       }

}

5 代码说明:

(1)指定 WebService 的命名空间和调用方法

import org.ksoap2.serialization.SoapObject;

private static final String NAMESPACE = "http://WebXml.com.cn/";

private static final String METHOD_NAME = "getWeatherbyCityName";

SoapObject rpc = new SoapObject(NAMESPACE, METHOD_NAME);

SoapObject类的第一个参数表示WebService的命名空间,可以从WSDL文档中找到WebService的命名空间。

第二个参数表示要调用的WebService方法名。

(2) 设置调用方法的参数值,如果没有参数,可以省略,设置方法的参数值的代码如下:

rpc.addProperty("theCityName", "苏州");

要注意的是,addProperty方法的第1个参数虽然表示调用方法的参数名,但该参数值并不一定与服务端的WebService类中的方法参数名一致,只要设置参数的顺序一致即可。

(3) 生成调用Webservice方法的SOAP请求信息。

SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);

envelope.bodyOut = rpc;

envelope.dotNet = true;

envelope.setOutputSoapObject(rpc);

创建SoapSerializationEnvelope对象时需要通过SoapSerializationEnvelope类的构造方法设置SOAP协议的版本号。

该版本号需要根据服务端WebService的版本号设置。

在创建SoapSerializationEnvelope对象后,不要忘了设置SOAPSoapSerializationEnvelope类的bodyOut属性, 该属性的值就是在第一步创建的SoapObject对象。

(4)、创建HttpTransportsSE对象。

这里不要使用 AndroidHttpTransport ht = new AndroidHttpTransport(URL); 这是一个要过期的类

private static String URL = "http://www.webxml.com.cn/webservices/weatherwebservice.asmx";

HttpTransportSE ht = new HttpTransportSE(URL); ht.debug = true;

(5) 使用call方法调用WebService方法

private static String SOAP_ACTION = "http://WebXml.com.cn/getWeatherbyCityName";

ht.call(SOAP_ACTION, envelope);

SOAP_ACTION=命名空间+方法名

(6) 获得WebService方法的返回结果

有两种方法:

A、使用getResponse方法获得返回数据。

private SoapObject detail;

detail =(SoapObject) envelope.getResponse();

B、使用 bodyIn 及 getProperty。

private SoapObject detail;

SoapObject result = (SoapObject)envelope.bodyIn;

detail = (SoapObject) result.getProperty("getWeatherbyCityNameResult");

(7) Android 中在代码中为了调试写了system.out.print()输出项

在菜单:Window-->show view-->other-->找到Android,选择Logcat 是可以看到输出的,

如果你想在一个单独的窗口看到system.out.print()的输出的话,可以在logcat界面点那个绿色的“+”号。

在Filter name 和 By log tag里面均填入System.out,这样的话你就能在单独的界面查看system.out.print()的输出了!!

(8) Toast是Android中用来显示显示信息的一种机制,和Dialog不一样的是,Toast是没有焦点的,而且Toast显示的时间有限,过一定的时间就会自动消失。

 

posted @ 2013-06-20 23:04  jhtchina  阅读(587)  评论(0)    收藏  举报