Android通过Soap请求Webservice共通

Posted on Leave a commentPosted in Android

好久都没写了,今天总结的是Android中通过Soap协议访问Webservice共通类。
首先下载一个第三方jar包k2soap-android-timeout.jar 将下载的文件 放到libs 文件夹下。
实现思路
新建一个接口ServiceCallBack用来传递数据

package org.shuaibi.exploration.utils;

import org.json.JSONObject;

/**
 *
 * @author ZeroX
 *
 */
public interface ServiceCallBack {
	/**
	 * 接口返回值
	 * @param jsonObject 返回的json
	 * @param mark 调用接口时传的标识
	 */
	public void ServiceResult(JSONObject jsonObject,int mark);
}

新建CallWebservice类继承Thread 在线程里面请求网络,然后后将返回的数据发给主线程,最后通过ServiceCallBack发送给Activity ,再在Activity 里处理返回的数据 废话不多说 直接上代码

package org.shuaibi.exploration.utils;

import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map.Entry;

import org.apache.http.conn.ConnectTimeoutException;
import org.json.JSONException;
import org.json.JSONObject;
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.annotation.SuppressLint;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.widget.Toast;



@SuppressLint("HandlerLeak")
public class CallWebServiceBySoap extends Thread{
	private String method,httphost;
	private HashMap<String, String> params;
	private Context context;
	private ServiceCallBack serviceCallBack;
	private int mark;

	/**
	 * Activity访问WebService
	 * @param context 上下文 一定要传 this
	 * @param method 方法名称
	 * @param params 参数名称 
	 * @param serviceName service名
	 * @param mark 标记
	 */
	public CallWebServiceBySoap(Context context,String method, HashMap<String, String> params, String httpHost,int mark)
	{
		this.method=method;
		this.params=params;
		this.httphost=httpHost;
		this.context=context;
		this.serviceCallBack=(ServiceCallBack) context;
		this.mark=mark;
	}

	/**
	 * Fragment访问WebService
	 * @param context 上下文 一定要传 this
	 * @param method 方法名称
	 * @param params 参数名称 
	 * @param serviceName service名
	 * @param mark 标记
	 */
	public CallWebServiceBySoap(Fragment fragment,String method, HashMap<String, String> params, String httpHost,int mark)
	{
		this.method=method;
		this.params=params;
		this.httphost=httpHost;
		this.context=fragment.getActivity();
		this.serviceCallBack=(ServiceCallBack) fragment;
		this.mark=mark;
	}

	@Override
	public void run() {
		super.run();
		Message message=new Message();
		try {
			message.what=1;

			message.obj=getJSONObject(method,params,httphost);
		}catch(ConnectTimeoutException e){
			message.what=-5;
			e.printStackTrace();

		}catch (IOException e) {
			message.what=-5;

			e.printStackTrace();
		}catch (XmlPullParserException e) {

			message.what=-6;
			e.printStackTrace();
		} catch (JSONException e) {

			message.what=-7;
			e.printStackTrace();
		}
		resuleHandler.sendMessage(message);
	}


	Handler resuleHandler=new Handler()
	{
		public void handleMessage(android.os.Message msg) {
			try {

				switch(msg.what)
				{
				case 1:
					int result=((JSONObject)msg.obj).getInt("result");
					switch(result){
					case 1: //状态为1将数据 发到Activity处理
						serviceCallBack.ServiceResult((JSONObject)msg.obj, mark);
						break;
					default ://其他状态 弹出提示信息
						Toast.makeText(context,((JSONObject)msg.obj).getString("msg"), Toast.LENGTH_SHORT).show();
						break;
					}

					break;
				case -5:
					if(Config.NETWORKNUM==0){
						Config.NETWORKNUM++;
						Toast.makeText(context,"连接服务器失败,请检查网络!", Toast.LENGTH_SHORT).show();
					}
					break;
				case -6:
					if(Config.NETWORKNUM==0){
						Config.NETWORKNUM++;
						Toast.makeText(context,"数据解析异常,请稍后再试!", Toast.LENGTH_SHORT).show();
					}
					break;
				case -7: 
					if(Config.NETWORKNUM==0){
						Config.NETWORKNUM++;
						Toast.makeText(context,"返回数据异常!", Toast.LENGTH_SHORT).show();
					}
					break;
				default:

					if(Config.NETWORKNUM==0){
						Config.NETWORKNUM++;
						Toast.makeText(context, "连接服务器失败,请检查网络", Toast.LENGTH_SHORT).show();
					}
					break;
				}
			} catch (JSONException e) {
				Toast.makeText(context, "数据处理异常,请稍后再试", Toast.LENGTH_SHORT).show();
				e.printStackTrace();
			}
		};
	};

	public static JSONObject getJSONObject(String method, HashMap<String, String> params, String httphost) throws IOException, XmlPullParserException, JSONException  {
		String wsdlURL = "http://" + Config.WEBSERVICE_IP + httphost;
		String webMethod = method;
		String namespace = Config.NAME_SPACE;
		String soapAction = namespace + webMethod;
		// 步骤2 创建一个SoapObject对象
		SoapObject soapObject = new SoapObject(namespace, webMethod);
		if(params!=null){
			// 步骤3 传递参数
			Iterator<Entry<String, String>> iterator = params.entrySet().iterator();
			// 循环读取 传递参数
			while (iterator.hasNext()) {
				Entry<String, String> obj = (Entry<String, String>) iterator.next();
				// 将参数添加到SoapObject对象中
				soapObject.addProperty(obj.getKey().toString(), obj.getValue().toString());
			}
		}
		// 步骤4 创建SoapSerializationEnvelope
		SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
		envelope.dotNet = true;
		// 步骤5 设置一下传回对象
		envelope.bodyOut = soapObject;
		envelope.setOutputSoapObject(soapObject);
		// 步骤6 创建HttpTransportSE用于传输对象
		HttpTransportSE se = new HttpTransportSE(wsdlURL, 1000 * 10);
		JSONObject jsonObject = null;
		se.call(soapAction, envelope);
		// 步骤8获取从webService返回的结果
		if (envelope.getResponse() != null) {
			jsonObject = new JSONObject(envelope.getResponse().toString());
			Config.NETWORKNUM=0;
		}
		return jsonObject;
	}



}

 

使用方法


package org.shuaibi.exploration.activity;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.ViewById;
import org.json.JSONObject;
import org.shuaibi.exploration.R;
import org.shuaibi.exploration.utils.CallWebServiceByPost;
import org.shuaibi.exploration.utils.ServiceCallBack;

import android.os.Bundle;
import android.widget.TextView;
import android.app.Activity;
/**
 *
 * @author ZeroX
 *
 */
@EActivity(R.layout.activity_main)
public class MainActivity extends Activity implements ServiceCallBack {

	private final int GETIMG=1;
	private int num=10;

	@ViewById(R.id.tv_result)
	public TextView tv_result;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	}

	@AfterViews
	public void initData()
	{
		//请求WebService
		new CallWebServiceByPost(this, "meinv?num="+num, null, GETIMG).start();
	}

	@Override
	public void ServiceResult(JSONObject jsonObject, int mark) {
		switch (mark) {
		case GETIMG:
			//处理接口返回值
			tv_result.setText(jsonObject.toString());
			break;

		default:
			break;
		}

	}

}