Android 调用webService+回调接口+线程池工具类封装(支持json格式接口和xml格式接口)

Posted 静思浅行

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Android 调用webService+回调接口+线程池工具类封装(支持json格式接口和xml格式接口)相关的知识,希望对你有一定的参考价值。

由于webService 使用的soap协议不是http协议,需要添加支持jar包,ksoap2-android-assembly-2.5.4-jar-with-dependencies.jar

支持json格式接口和xml格式接口

项目中服务器地址是支持手动配置的,所以地址会手动从sp中读取,大家可以根据需要自行修改。


-----------------------------------------------------

封装后的工具类

WebServiceUtils 
------------------------------------------------------

package com.yingde.onlinelaw2.utils;

import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.apache.http.client.HttpResponseException;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.AndroidHttpTransport;
import org.xmlpull.v1.XmlPullParserException;

import android.os.Handler;
import android.os.Looper;
import android.os.Message;

import com.yingde.onlinelaw2.base.BaseApplication;
import com.yingde.onlinelaw2.base.Constants;
import com.yingde.onlinelaw2.bean.Soap;
import com.yingde.onlinelaw2.utils.http.URLTool;

/**
 * Created by Administrator on 2016/9/21.
 * 访问WebService的工具类,
 */
public class WebServiceUtils 
    private static final String TAG = "WebServiceUtils";
    // 含有3个线程的线程池
    private static final ExecutorService executorService = Executors
            .newFixedThreadPool(3);

    // 命名空间
    private static final String NAMESPACE = URLTool.NAME_SPACE;

    private static final int TIMEOUT = Common.TIME_OUT;//超时时间

    /**
     * json格式结果
     *
     * @param methodName         WebService的调用方法名
     * @param properties         WebService的参数
     * @param webServiceCallBack 回调接口
     */
    public static void callWebService(final String methodName,
                                      HashMap<String, Object> properties,
                                      final WebServiceCallBack webServiceCallBack) 

        String http = (String) SPUtils.get(BaseApplication.context, Common.KEY_HTTP, URLTool.HTTP);
        String ip = (String) SPUtils.get(BaseApplication.context, Common.KEY_IP, URLTool.IP);
        String port = (String) SPUtils.get(BaseApplication.context, Common.KEY_PORT, URLTool.PORT);
        //服务器地址
        String baseURL = http + ip + ":" + port + URLTool.WEB_SERVICE;

        // 创建HttpTransportSE对象, url timeOut
        final AndroidHttpTransport httpTransportSE = new AndroidHttpTransport(baseURL, TIMEOUT);
        // 创建SoapObject对象
        SoapObject soapObject = new SoapObject(NAMESPACE, methodName);
        LogUtils.e(TAG, "NAME_SPACE:" + NAMESPACE + "\\nURL:" + baseURL + "\\nwebServices请求开始\\nmethodName: " + methodName + "\\nparams: " + properties.toString());

        // SoapObject添加参数
        if (properties != null) 
            for (Iterator<Map.Entry<String, Object>> it = properties.entrySet()
                    .iterator(); it.hasNext(); ) 
                Map.Entry<String, Object> entry = it.next();
                soapObject.addProperty(entry.getKey(), entry.getValue());
            
        

        // 实例化SoapSerializationEnvelope,传入WebService的SOAP协议的版本号
        final SoapSerializationEnvelope soapEnvelope = new SoapSerializationEnvelope(
                SoapEnvelope.VER11);
        // 设置是否调用的是.Net开发的WebService
        soapEnvelope.setOutputSoapObject(soapObject);
        soapEnvelope.dotNet = true;
        httpTransportSE.debug = true;

        // 用于子线程与主线程通信的Handler
        final Handler mHandler = new Handler(Looper.getMainLooper()) 

            @Override
            public void handleMessage(Message msg) 
                super.handleMessage(msg);
                // 将返回值回调到callBack的参数中
                webServiceCallBack.callBack((String) msg.obj);
            
        ;

        // 开启线程去访问WebService
        executorService.submit(new Runnable() 

            @Override
            public void run() 
                String resultJson = "";
                try 
                    httpTransportSE.call(NAMESPACE + methodName, soapEnvelope);
                    if (soapEnvelope.getResponse() != null) 
                        // 获取服务器响应返回的SoapObject
//                        resultSoapObject = (SoapObject) soapEnvelope.bodyIn;
                        resultJson = soapEnvelope.getResponse().toString();
                        LogUtils.d(TAG,methodName+ " -- webServices返回结果:" + resultJson);
                    
                 catch (HttpResponseException e) 
                    e.printStackTrace();
                    resultJson = null;
                 catch (IOException e) 
                    e.printStackTrace();
                    resultJson = null;
                 catch (XmlPullParserException e) 
                    e.printStackTrace();
                    resultJson = null;
                 finally 
                    // 将获取的消息利用Handler发送到主线程
                    mHandler.sendMessage(mHandler.obtainMessage(0,
                            resultJson));
                
            
        );
    

    /**
     * 返回的xml 格式的接口
     * @param methodName
     * @param soaps
     * @param soapCalback
     */
    public static void callWebServiceSoap(final String methodName,
                                          List<Soap> soaps,
                                          final WebServiceCallBackSoap soapCalback) 

        String http = (String) SPUtils.get(BaseApplication.context, Common.KEY_HTTP, URLTool.HTTP);
        String ip = (String) SPUtils.get(BaseApplication.context, Common.KEY_IP, URLTool.IP);
        String port = (String) SPUtils.get(BaseApplication.context, Common.KEY_PORT, URLTool.PORT);
        //服务器地址
        String baseURL = http + ip + ":" + port + URLTool.WEB_SERVICE;

        // 创建HttpTransportSE对象,传递WebService服务器地址  url timeOut
//        final HttpTransportSE httpTransportSE = new HttpTransportSE(URLTool.BASE_URL,5000);
        final AndroidHttpTransport httpTransportSE = new AndroidHttpTransport(Constants.URL, TIMEOUT);
        // 创建SoapObject对象
        SoapObject soapObject = new SoapObject(NAMESPACE, methodName);
        LogUtils.e(TAG, "NAME_SPACE:" + soaps.toString() + NAMESPACE + "\\nURL:" + baseURL + "" + "\\nparams:" + soaps.toString() + "\\nwebServices请求开始\\nmethodName: " + methodName);

        // SoapObject添加参数
        for (Soap soap : soaps) 
            soapObject.addProperty(soap.getName(), soap.getValue());
        

        // 实例化SoapSerializationEnvelope,传入WebService的SOAP协议的版本号
        final SoapSerializationEnvelope soapEnvelope = new SoapSerializationEnvelope(
                SoapEnvelope.VER11);
        // 设置是否调用的是.Net开发的WebService
        soapEnvelope.setOutputSoapObject(soapObject);
        soapEnvelope.dotNet = true;
        httpTransportSE.debug = true;

        // 用于子线程与主线程通信的Handler
        final Handler mHandler = new Handler() 

            @Override
            public void handleMessage(Message msg) 
                super.handleMessage(msg);
                // 将返回值回调到callBack的参数中
                soapCalback.callBackSoap((SoapObject) msg.obj);
            

        ;

        // 开启线程去访问WebService
        executorService.submit(new Runnable() 

            @Override
            public void run() 
                SoapObject resultSoapObject = null;
                try 
                    httpTransportSE.call(NAMESPACE + methodName, soapEnvelope);
                    if (soapEnvelope.getResponse() != null) 
                        // 获取服务器响应返回的SoapObject
                        resultSoapObject = (SoapObject) soapEnvelope.getResponse();
                        LogUtils.e(methodName+" -- webServices返回结果:"+resultSoapObject.toString());
                    
                 catch (HttpResponseException e) 
                    e.printStackTrace();
                    LogUtils.e(TAG, e.getMessage());
                    resultSoapObject = null;
                 catch (IOException e) 
                    e.printStackTrace();
                    LogUtils.e(TAG, e.getMessage());
                    resultSoapObject = null;
                 catch (XmlPullParserException e) 
                    e.printStackTrace();
                    LogUtils.e(TAG, e.getMessage());
                    resultSoapObject = null;
                 finally 
                    // 将获取的消息利用Handler发送到主线程
                    mHandler.sendMessage(mHandler.obtainMessage(0, resultSoapObject));
                
            
        );
    


    /**
     * @author xiaanming
     */
    public interface WebServiceCallBack 
        public void callBack(String result);
    

    /**
     * xml格式结果接口
     */
    public interface WebServiceCallBackSoap 
        public void callBackSoap(SoapObject soapObject);
    


 
 
 
---------------------------
调用如下
---------------------------
/**
 * 上传地理位置
 *
 * @param lat_gps      gps获取的lat
 * @param lng_gps      gps获取的lng
 */
private void uploadLocation(String lat_gps, String lng_gps) 
    if (!NetworkUtils.isNetworkAvailable(mContext)) 
        return;
    

    HashMap<String, Object> params = new HashMap<>();
    params.put("ID", SPUtils.get(mContext, Common.KEY_ID, ""));
    params.put("X", lng_jz);
    params.put("Y", lat_jz);
    params.put("UserInfo", SPUtils.get(mContext, Common.KEY_USER_INFO, ""));
    
    WebServiceUtils.callWebService(URLTool.Update_User_XY2, params, new WebServiceUtils.WebServiceCallBack() 
        @Override
        public void callBack(String result) 
            if (result != null) 
                Gson gson = new Gson();
                BaseBean baseBean = gson.fromJson(result, BaseBean.class);
                if (baseBean.getResult() == 1) 
                    LogUtils.e(TAG, "地理位置更新成功!");
                 else if (baseBean.getResult() == 0) 
                    LogUtils.e(TAG, "地理位置更新失败," + baseBean.getMessage());
                
             else 
                LogUtils.e(TAG, "地理位置更新失败,请求超时!");
            
        
    );


 
 

以上是关于Android 调用webService+回调接口+线程池工具类封装(支持json格式接口和xml格式接口)的主要内容,如果未能解决你的问题,请参考以下文章

黑马Android(14)webservice概念/调用/wsdl接口

android调用webservice接口获取信息

webservice接口第二次调用接口不通

ANDROID调用webservice带soapheader验证

如何实现webservice的异步调用

Android开发:ViewPager的回调接口解析