---
title: "Android学习13-----网络通信(3) 与Web Service进行通讯"
author: "xdwangiflytek"
date: "2012-11-26T09:40:15Z"
tags: []
categories: ["移动开发"]
slug: "android-13-3-web-service"
draft: false
lastmod: "2012-11-26T09:40:15Z"
id: 1728480
url: "https://xdwangiflytek.iteye.com/blog/1728480"
---

这里我们的WebService使用xFire开发。  
首先开发服务器端，为了方便我们使用MyEclipse开发WebService  
定义文件操作的接口IFileServices.java

```
package com.iflytek.services;

public interface IFileServices {

	/**
	 * 文件的保存
	 * 
	 * @param fileName
	 *            文件名称
	 * @param content
	 *            文件的内容
	 * @throws Exception
	 */
	public void save(String fileName, String content) throws Exception;

	/**
	 * 文件的读取
	 * 
	 * @param fileName
	 *            文件名称
	 * @return
	 * @throws Exception
	 */
	public String load(String fileName) throws Exception;

}

```

实现类FileServicesImpl.java

```
package com.iflytek.services.impl;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.PrintStream;
import java.util.Scanner;

import com.iflytek.services.IFileServices;

public class FileServicesImpl implements IFileServices {

	public String load(String fileName) throws Exception {
		File file = new File("D:" + File.separator + "xdwang" + File.separator
				+ fileName);
		if (!file.exists()) { // 文件不存在
			return null;
		}
		StringBuffer buf = new StringBuffer();
		Scanner scan = new Scanner(new FileInputStream(file));
		scan.useDelimiter("\n");
		while (scan.hasNext()) {
			buf.append(scan.next());
		}
		scan.close();
		return buf.toString();
	}

	public void save(String fileName, String content) throws Exception {
		File file = new File("D:" + File.separator + "xdwang" + File.separator
				+ fileName);
		if (!file.getParentFile().exists()) {
			file.getParentFile().mkdirs();
		}
		PrintStream out = new PrintStream(new FileOutputStream(file));
		out.print(content);
		out.close();
	}

}

```

配置services.xml

```
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://xfire.codehaus.org/config/1.0">
	<service>
		<name>iflytek</name>
		<serviceClass>
			com.iflytek.services.IFileServices
		</serviceClass>
		<implementationClass>
			com.iflytek.services.impl.FileServicesImpl
		</implementationClass>
		<style>wrapped</style>
		<use>literal</use>
		<scope>application</scope>
	</service>
</beans>
```

 

这时，在浏览器上输入：

[http://IP:8080/AndroidWebServiceProject/services/iflytek?wsdl](http://IP:8080/AndroidWebServiceProject/services/iflytek?wsdl) ，即可打开，为此一个 Web Service 程序的服务器端就开发完成了，下面我们进行 Android 客户端程序的开发。

Android 程序要调用 Web Service 程序，并不像调用 JSP/Servlet 或 Socket 程序那样直接使用系统提供的类完成，因为 Android 中并没有提供直接与 WebService 互调用的操作类库，所以必须依靠第三方提供的类库才可以完成，比较常用的就是 ksoap 类库，可以到 [http://code.google.com/p/ksoap2-android/](http://code.google.com/p/ksoap2-android/) 上进行下载。

下载过后，将其配置到 Android 项目的 Java Build Path 中即可，配置完成之后，即可在 Android 中编写程序调用 WebService 程序，具体步骤如下：

1、 通过 org.ksoap2.serialization.SoapObject 类来指定要调用的 WebService 程序所需要的命名控件，而 SoapObject 类的常用方法如下：

**No.**

**方法**

**描述**

1

Public SoapObject(String namespace,String name)

实例化 SoapObject 类对象

2

Public String getName()

取得要调用的方法名称

3

Public String getNameSpace()

取得 Soap 对象的命名空间

4

Public Object getProperty(java.lang.String name)

取得指定名称的属性

5

Public SoapObject addProperty(String name,Object value)

设置调用 WebService 方法时所需要的参数

2、 取得 SoapObject 的实例化对象之后，即可通过 SoapObject 类的 addProperty() 方法设置调用 save() 方法时所需要的参数，而设置的顺序要与 Web Service 程序端的 save() 方法的参数顺序符合，在调用 addProperty() 方法时，不一定非要和服务器端上的方法名称、参数名称一样，因为程序在执行时也只是根据设置参数的顺序来决定，而不是根据名称。

3、 生成调用 WebService 程序的 SOAP 请求信息，此时可以利用 org.ksoap2.serialization.SoapSerializationEnvelope 类完成，此类的常用方法如下：

**No.**

**方法、常量、属性**

**类型**

**描述**

1

Public static final int VER11

常量

使用 SOAP 11 版本操作

2

Public Object bodyIn

属性

封装输入的 SoapObject 对象

3

Public Object bodyOut

属性

封装输出的 SoapObject 对象

4

Public Boolean dotNet

属性

是否为 .NET 连接，此处设置为 false ，如果设置为 true ，则服务器端无法接受请求参数

5

Public SoapSerializationEnvelope(int version)

构造

实例化 SoapSerializationEnvelope 类对象

6

Public void setOutputSoapObject(Object soapObject)

普通

设置要输出的 SoapObject 对象

4、 创建 org.ksoap2.transport.HttpTransportSE 类对象，并且利用此对象调用 WebService 端的操作方法，此类的常用操作如下：

**No.**

**方法、属性**

**描述**

1

Public Boolean debug

是否调试，如果设置为 true ，则表示调试

2

Public HttpTransportSE(String url)

实例化 HttpTransportSE 类的对象

3

public void call(String soapAction, SoapEnvelope envelope) throws IOException, XmlPullParserException

调用 WebService 端的操作方法

5、 接受 WebService 的返回值

Android 客户端代码

WebServiceActivity.java

```
package com.iflytek.demo;

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;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class WebServiceActivity extends Activity {

	private Button saveBtn = null;
	private Button loadBtn = null;
	private TextView showTxt = null;
	/**
	 * 需要调用WebService的命名空间
	 */
	private static final String NAMESPACE = "http://IP/";
	/**
	 * 服务的地址，不需要*.wsdl
	 */
	private static String URL = "http://IP:8080/AndroidWebServiceProject/services/iflytek";
	/**
	 * 需要调用的保存方法
	 */
	private static final String SAVE_METHOD_NAME = "save";
	/**
	 * 需要调用的读取方法
	 */
	private static final String LOAD_METHOD_NAME = "load";
	private static String SOAP_ACTION = "http://IP:8080/AndroidWebServiceProject/services/";

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		this.saveBtn = (Button) super.findViewById(R.id.save);
		this.loadBtn = (Button) super.findViewById(R.id.load);
		this.showTxt = (TextView) super.findViewById(R.id.show);
		this.saveBtn.setOnClickListener(new SaveOnClickListenerImpl());
		this.loadBtn.setOnClickListener(new LoadOnClickListenerImpl());
	}

	private class SaveOnClickListenerImpl implements OnClickListener {

		@Override
		public void onClick(View v) {
			final AsyncTask<Void, Void, String> task = new AsyncTask<Void, Void, String>() {

				@Override
				protected void onPostExecute(String result) {
					Toast.makeText(WebServiceActivity.this, "数据保存成功",
							Toast.LENGTH_SHORT).show();
				}

				@Override
				protected void onPreExecute() {
					super.onPreExecute();
				}

				@Override
				protected String doInBackground(Void... arg0) {
					SoapObject soapObject = new SoapObject(NAMESPACE,
							SAVE_METHOD_NAME);
					soapObject.addProperty("fileName", "xdwang.txt");// 设置参数
					soapObject.addProperty("content", "Hello, xdwang ");
					SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
							SoapEnvelope.VER11);// 给出版本号
					envelope.bodyOut = soapObject;// 输出对象
					envelope.dotNet = false;// 不是.NET服务器
					envelope.setOutputSoapObject(soapObject);// 输出SoapObjet
					HttpTransportSE trans = new HttpTransportSE(URL);// 指定地址
					trans.debug = true; // 使用调试功能
					try {
						trans.call(SOAP_ACTION, envelope);// 调用方法
					} catch (IOException e) {
						e.printStackTrace();
					} catch (XmlPullParserException e) {
						e.printStackTrace();
					}
					return null;
				}
			};
			task.execute();
		}

	}

	private class LoadOnClickListenerImpl implements OnClickListener {

		@Override
		public void onClick(View v) {

			final AsyncTask<Void, Void, String> task = new AsyncTask<Void, Void, String>() {

				@Override
				protected void onPostExecute(String result) {
					WebServiceActivity.this.showTxt
							.setText("Web Service返回的数据是：" + result);
				}

				@Override
				protected void onPreExecute() {
					super.onPreExecute();
				}

				@Override
				protected String doInBackground(Void... arg0) {
					SoapObject soapObject = new SoapObject(NAMESPACE,
							LOAD_METHOD_NAME);
					soapObject.addProperty("fileName", "xdwang.txt");// 设置参数
					SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
							SoapEnvelope.VER11);// 给出版本号
					envelope.bodyOut = soapObject;// 输出对象
					envelope.dotNet = false;// 不是.NET服务器
					envelope.setOutputSoapObject(soapObject);// 输出SoapObjet
					HttpTransportSE trans = new HttpTransportSE(URL);// 指定地址
					trans.debug = true; // 使用调试功能
					try {
						trans.call(SOAP_ACTION, envelope);// 调用方法
					} catch (IOException e) {
						e.printStackTrace();
					} catch (XmlPullParserException e) {
						e.printStackTrace();
					}
					SoapObject result = (SoapObject) envelope.bodyIn;// 接收返回值
					return result.getProperty(0).toString();
				}
			};
			task.execute();

		}

	}
}
```

main.xml

```
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 
	xmlns:android="http://schemas.android.com/apk/res/android"
	android:orientation="vertical" 
	android:layout_width="fill_parent"
	android:layout_height="fill_parent">
	<Button
		android:id="@+id/save" 
		android:layout_width="fill_parent"
		android:layout_height="wrap_content" 
		android:text="通过WebService保存文件" />
	<Button
		android:id="@+id/load" 
		android:layout_width="fill_parent"
		android:layout_height="wrap_content" 
		android:text="通过WebService读取文件" />
	<TextView
		android:id="@+id/show" 
		android:layout_width="fill_parent"
		android:layout_height="wrap_content" 
		android:text="显示文件读取内容" />
</LinearLayout>

```

AndroidManifest.xml

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