Android学习13-----网络通信(3) 与Web Service进行通讯
这里我们的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,即可打开,为此一个WebService程序的服务器端就开发完成了,下面我们进行Android客户端程序的开发。
Android程序要调用Web Service程序,并不像调用JSP/Servlet或Socket程序那样直接使用系统提供的类完成,因为Android中并没有提供直接与WebService互调用的操作类库,所以必须依靠第三方提供的类库才可以完成,比较常用的就是ksoap类库,可以到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(intversion)
构造
实例化SoapSerializationEnvelope类对象
6
Public void setOutputSoapObject(ObjectsoapObject)
普通
设置要输出的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. */@Overridepublic 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 {@Overridepublic void onClick(View v) {final AsyncTask<Void, Void, String> task = new AsyncTask<Void, Void, String>() {@Overrideprotected void onPostExecute(String result) {Toast.makeText(WebServiceActivity.this, "数据保存成功",Toast.LENGTH_SHORT).show();}@Overrideprotected void onPreExecute() {super.onPreExecute();}@Overrideprotected 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);// 输出SoapObjetHttpTransportSE 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 {@Overridepublic void onClick(View v) {final AsyncTask<Void, Void, String> task = new AsyncTask<Void, Void, String>() {@Overrideprotected void onPostExecute(String result) {WebServiceActivity.this.showTxt.setText("Web Service返回的数据是:" + result);}@Overrideprotected void onPreExecute() {super.onPreExecute();}@Overrideprotected 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);// 输出SoapObjetHttpTransportSE 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"><Buttonandroid:id="@+id/save" android:layout_width="fill_parent"android:layout_height="wrap_content" android:text="通过WebService保存文件" /><Buttonandroid:id="@+id/load" android:layout_width="fill_parent"android:layout_height="wrap_content" android:text="通过WebService读取文件" /><TextViewandroid: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" />
页:
[1]