Webservice请求以及个人简单的封装分享

Webservice是基于SOAP协议的数据请求,需要第三方jar包Ksoap2

这里贴下封装类的代码:

public class WebServiceUtils {
    // 含有3个线程的线程池
    private static final ExecutorService executorService = Executors.newFixedThreadPool(3);

    /**
     *
     * @param url
     *            WebService服务器地址
     * @param nameSpace
     *            WebService的命名空间
     * @param methodName
     *            WebService的调用方法名
     * @param properties
     *            WebService的参数
     * @param webServiceCallBack
     *            回调接口
     */
    public static void callWebService(String url, final String nameSpace, final String methodName, HashMap properties,
                                      final WebServiceCallBack webServiceCallBack) {
        // 创建HttpTransportSE对象,传递WebService服务器地址
        final HttpTransportSE httpTransportSE = new HttpTransportSE(url);
        // 创建SoapObject对象
        SoapObject soapObject = new SoapObject(nameSpace, methodName);

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

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

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

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

        };

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

            @Override
            public void run() {
                SoapObject resultSoapObject = null;
                try {
                    httpTransportSE.call(null, soapEnvelope);
                    if (soapEnvelope.getResponse() != null) {
                        // 获取服务器响应返回的SoapObject
                        resultSoapObject = (SoapObject) soapEnvelope.bodyIn;
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (XmlPullParserException e) {
                    e.printStackTrace();
                } finally {
                    // 将获取的消息利用Handler发送到主线程
                    Message mess = mHandler.obtainMessage(0,resultSoapObject);
                    mHandler.sendMessage(mess);
                }
            }
        });
    }

    //请求数据返回的结果的回调接口
    public interface WebServiceCallBack {
         void callBack(SoapObject result);
    }
}

这里值得注意的一点,如果要做文件上传的话,比如图片上传到服务器,参数dotNet一定要设置为false,不然上传文件不会成功!!


写一个BaseActivity,然后代码如下:

public class BaseActivity extends AutoLayoutActivity {//AutoLayout是一个第三方的类库,用于屏幕适配用的

    protected boolean isOneLoad = true;//是否需要第一次加载数据
    protected PopWindowUtils utils;//popupwindow的工具类
    protected PopupWindow window;
    protected HashMap mHashMap;//用于存放多次不一样的请求数据的参数等数据
    protected boolean flag = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mHashMap = new HashMap<>();
        utils = new PopWindowUtils(getWindow(), this);
        init();
        OneKeyBack.addActivity(this);
    }

    //初始化方法,子类初始化数据的地方
    public void init() {

    }

    //若要在一个Activity启动时候去显示一个popupwindow会报错,两种解决方法一种就是写在下面这     个方法中即可,或者使用handler来延迟500毫秒左右去显示popupwindow
    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        oneLoader();
    }

    //第一次加载数据,默认加载初始化的第一个
    protected void oneLoader() {
        if (isOneLoad) {
            isOneLoad = false;
            showWindow();
            if (mHashMap.size() > 0) {
                loadDate(false, 1);
            }
        }
    }

    //展示popwindow的方法
    public void showWindow() {
        if (window != null && window.isShowing()) {
            return;
        }
        window = utils.getMyWindow();
        window.showAtLocation(utils.getView(), Gravity.CENTER, 0, 0);
    }

    //数据加载前的方法
    public void beforeLoadData(int key) {

    }

    //数据请求到了以后的方法
    public void afterLoadData(int key) {
        dismissWindow();
    }

    //popwindow消失方法
    public void dismissWindow() {
        if (window != null && window.isShowing()) {
            window.dismiss();
            window = null;
        }
    }

    //判断是否有网的方法
    public boolean isNetworkConnected(Context context) {
        if (context != null) {
            ConnectivityManager mConnectivityManager = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
            if (mNetworkInfo != null) {
                return mNetworkInfo.isAvailable();
            }
        }
        return false;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        OneKeyBack.removeActivity(this);
        mHashMap.clear();
    }

    /**
     * 初始化数据的方法
     *
     * @param key        放入map的键
     * @param webService webservice对象
     * @param pageSize   请求数据每页的数量
     * @param increment  xlistview每次加载的数量
     * @param listView   xlistview的实例
     */
    public void initData(final int key, WebService webService, int pageSize, int increment, XListView listView) {
        if (mHashMap.size() > 0 && mHashMap.containsKey(key)) {
            return;
        }
        BaseBean baseBean = new BaseBean();
        baseBean.setWebService(webService);
        baseBean.setIncrement(increment);
        baseBean.setPageSize(pageSize);
        baseBean.setListView(listView);
        if (listView != null) {
            listView.setPullLoadEnable(true);
            listView.setPullRefreshEnable(true);
            listView.setXListViewListener(new XListView.IXListViewListener() {
                @Override
                public void onRefresh() {
                    loadDate(false, key);
                }

                @Override
                public void onLoadMore() {
                    loadDate(true, key);
                }
            });
        }
        mHashMap.put(key, baseBean);
    }

    public void initData(int key, WebService webService, int pageSize) {
        initData(key, webService, pageSize, 0, null);
    }

    public void initData(int key, WebService webService) {
        initData(key, webService, 0, 0, null);
    }

    //数据请求的封装
    protected void loadDate(final boolean isIncrement, final int key) {
        if (!mHashMap.containsKey(key)) {
            return;
        }
        final BaseBean baseBean = mHashMap.get(key);
        if (isNetworkConnected(this)) {
            flag = false;
            beforeLoadData(key);
            final WebService webService = baseBean.getWebService();
            if (baseBean.getIncrement() != 0) {
                if (isIncrement) {
                    baseBean.setPageSize(baseBean.getPageSize() + baseBean.getIncrement());
                    webService.getMap().put("pageSize", baseBean.getPageSize());
                }
            }
            WebServiceUtils.callWebService(
                    webService.getUrl(),
                    webService.getNameSpace(),
                    webService.getMethod(),
                    webService.getMap(),
                    new WebServiceUtils.WebServiceCallBack() {
                        @Override
                        public void callBack(SoapObject result) {
                            if (result != null) {
                                resultData(result, key);
                                afterLoadData(key);
                                if (baseBean.getListView() != null) {
                                    stopRefreshOrLoad(isIncrement, baseBean);
                                }
                            }
                        }
                    }
            );
        } else {
            if (baseBean.getListView() != null) {
                stopRefreshOrLoad(isIncrement, baseBean);
            }
            dismissWindow();
            if (!flag) {
                DialogUtils.showDialog(this, getWindow());
                flag = true;
            }
        }
    }

    //停止刷新或者加载
    protected void stopRefreshOrLoad(boolean isIncrement, BaseBean baseBean) {
        if (isIncrement) {
            baseBean.getListView().stopLoadMore();
        } else {
            baseBean.getListView().stopRefresh();
        }
    }

    //请求到的数据返回的方法
    protected void resultData(SoapObject result, int key) {

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (DialogUtils.builder != null) {
                WindowManager.LayoutParams attributes = getWindow().getAttributes();
                attributes.alpha = 1.0f;
                getWindow().setAttributes(attributes);
            }
        }
        return super.onKeyDown(keyCode, event);
    }
}

子类Acitivity直接继承BaseActivity,先调用initData()方法,按需传入对应的参数,若想在Activity显示的时候就去显示一个数据加载中...的popupwindow,只需要先initData()方法即可,然后重写resultData()方法,从参数中直接获得数据请求的结果来处理结果。有的地方不需要开始就加载一次数据,直接设置isOneLoad=false就可以了,init()方法里需要设置下绑定的布局文件,可以做一些控件或者数据初始化的处理。

initData()里对应的参数

1、Key值,用于对应beforeLoadData(),afterLoadData(),resultData()方法里的Key值,即初始化数据传入的Key是什么在请求数据过程中的方法中的参数对应的Key就是什么

2、Webservice实体类

public class BaseBean {
    private WebService webService;
    private  int pageSize;
    private int increment;
    private XListView listView;

    public WebService getWebService() {
        return webService;
    }

    public void setWebService(WebService webService) {
        this.webService = webService;
    }

    public int getPageSize() {
        return pageSize;
    }

    public void setPageSize(int pageSize) {
        this.pageSize = pageSize;
    }

    public int getIncrement() {
        return increment;
    }

    public void setIncrement(int increment) {
        this.increment = increment;
    }

    public XListView getListView() {
        return listView;
    }

    public void setListView(XListView listView) {
        this.listView = listView;
    }
}
3,4,5、初始加载的页数,Xlistview加载每次的增长量,Xlistview的实例,如果用到xlistview的地方较多,这里就可以做个封装(这里拿Xlistview为例,可根据使用的不同的控件去做改变) 一般做数据请求的时候给参数中有pagesize,这个根据API上给实际的参数去修改


如何去运用呢,在需要请求数据的地方设置好相应的参数,然后调用loadData(),在resultData()里去处理数据就好了,如果在数据请求前或者后要做什么操作直接调用beforeLoadData()和afterLoadData()即可,比如显示一个popupwindow什么的。这里popupwindow的工具类就不贴出来了。

写的不好的地方还希望指出和指教。



你可能感兴趣的:(android学习笔记)