---
title: "Android调用天气预报的WebService简单例子"
author: "mmdev"
date: "2012-12-05T18:09:00Z"
tags: []
slug: "android-webservice"
draft: false
lastmod: "2012-12-05T22:02:10Z"
id: 1742170
url: "https://mmdev.iteye.com/blog/1742170"
---

阶段一：进行主界面布局，如下图：

![](http://img.my.csdn.net/uploads/201212/05/1354702380_1290.jpg)

具体代码如下：

```
<LinearLayout 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:orientation="vertical" 
    android:background="@drawable/ba">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/input_city" />
    <EditText 
        android:id="@+id/city"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />
    <Button 
        android:id="@+id/search"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/search"/>

    <TextView 
        android:id="@+id/result"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>
</LinearLayout>
```

阶段二：导入KSOAP包.

将ksoap2-android-assembly-2.5.2-jar-with-dependencies.jar包拷贝到libs文件夹下，然后点击右键Build Path –&gt; Configure Build Path...，会出现

![](http://img.my.csdn.net/uploads/201212/05/1354700674_6524.jpg)

然后将添加的包勾上...

阶段三：调用天气预报的WebService

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

```
import org.ksoap2.serialization.SoapObject;
private static final String NAMESPACE = "http://WebXml.com.cn/";
private static final String METHOD_NAME = "getWeatherbyCityName";

SoapObject soapObject = 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 = soapObject;
envelope.dotNet = true;
envelope.setOutputSoapObject(soapObject);
```

创建SoapSerializationEnvelope对象时需要通过SoapSerializationEnvelope类的构造方法设置SOAP协议的版本号。  
该版本号需要根据服务端WebService的版本号设置。  
在创建SoapSerializationEnvelope对象后，不要忘了设置SOAPSoapSerializationEnvelope类的bodyOut属性，  
该属性的值就是在第一步创建的SoapObject对象。

4、创建HttpTransportsSE对象。

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

```
private static String wsdlUrl = "http://www.webxml.com.cn/webservices/weatherwebservice.asmx";
HttpTransportSE ht = new HttpTransportSE(wsdlUrl); 
```

```
ht.debug = true;
```

5、使用call方法调用WebService方法

```
private static String SOAP_ACTION = "http://WebXml.com.cn/getWeatherbyCityName";
ht.call(SOAP_ACTION, envelope);
```

网上有人说这里的call的第一个参数为null，但是经过我的测试，null是不行的。  
第2个参数就是在第3步创建的SoapSerializationEnvelope对象。

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、 这时候执行会出错，提示没有权限访问网络

需要修改 AndroidManifest.xml 文件，赋予相应权限

简单来说就是增加下面这行配置：&lt;uses-permission android:name="android.permission.INTERNET"&gt;&lt;/uses-permission&gt;

关于SOAPUtil类的完整代码如下：

```
package com.lks.weathersearch.soap;

import java.io.IOException;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import org.xmlpull.v1.XmlPullParserException;

public class SOAPUtil {

	public static Object doTransport(final String wsdlUrl,
			final String webMethod, String city) {
		String nameSpace = "http://WebXml.com.cn/";
		SoapObject soapObject = new SoapObject(nameSpace, webMethod);
		soapObject.addProperty("theCityName", city);
		System.out.println("city:"+city);
		SoapSerializationEnvelope serializationEnvelope = new SoapSerializationEnvelope(
				SoapEnvelope.VER11);
		serializationEnvelope.bodyOut = soapObject;
		serializationEnvelope.dotNet = true;
		serializationEnvelope.setOutputSoapObject(soapObject);
		HttpTransportSE httpTransportSE = new HttpTransportSE(wsdlUrl);

		String SOAP_ACTION = "http://WebXml.com.cn/" + webMethod;
		System.out.println("action:"+SOAP_ACTION);

		try {
			httpTransportSE.call(SOAP_ACTION, serializationEnvelope);
			if (serializationEnvelope.getResponse() != null) {
				SoapObject result = (SoapObject) serializationEnvelope.getResponse();
				System.out.println(result);
				return result;
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (XmlPullParserException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return null;
	}
}
```

阶段四：编写WeatherActivity,进行相应的事件处理.具体代码如下：

```
package com.lks.weathersearch.web;

import org.ksoap2.serialization.SoapObject;

import com.lks.weathersearch.soap.SOAPUtil;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.support.v4.app.NavUtils;
import android.text.Editable;

public class WeatherActivity extends Activity {

	EditText cityText;
	Button searchButton;
	TextView resultView;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_weather);
        cityText = (EditText) this.findViewById(R.id.city);
        searchButton = (Button) this.findViewById(R.id.search);
        resultView = (TextView) this.findViewById(R.id.result);
        
        searchButton.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				String city = cityText.getText().toString();
				String wsdlUrl = "http://www.webxml.com.cn/webservices/weatherwebservice.asmx";
				String webMethod = "getWeatherbyCityName";
				SoapObject result = (SoapObject) SOAPUtil.doTransport(wsdlUrl, webMethod, city);
				resultView.setText(result.getProperty(4).toString()+"\n"+result.getProperty(10).toString());
			}
		});
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_weather, menu);
        return true;
    }

    
}
```

运行结果显示：

![](http://img.my.csdn.net/uploads/201212/05/1354702444_4551.jpg)

相应的项目已上传到资源~欢迎下载~![微笑](http://static.blog.csdn.net/xheditor/xheditor_emot/default/smile.gif)