WebService+Rxjava

来源:互联网 发布:国信蓝点java培训 编辑:程序博客网 时间:2024/06/06 16:42

最近公司有了个新项目,是之前有个项目需要迭代.由于这个项目比较老.所以用的是WebService的接口.我之前都是写的是restful的接口.没有接触过WebServiece.看到之前的代码我也有点闷逼,于是就花了几天去研究了下WebService


WebSerivce 比 restful出现的早.所以像像我这这种工作两三年的有点都可能没有接触过WebService. WebService底层是依赖SOAP协议的,主要核心是面向活动的,而restful其实就是我们常用的get  post 等 ,他是面向资源的 . WebService最早是针对RPC的一种解决方案简单对象访问协议,默认参数数据格式是XML的,而Restful是针对网络应用设计的,设计了不同的请求状态,来降低来发的复杂度,提高系统的可伸缩性 .其实WebService和Restful没有什么区别,底层都是用HttpURLConnection实现的只是他们参数,请求头(报文)的拼接方式不同而已,在Restful中叫请求头,在WebService中叫报文. 

现在Retrofit + Rxjava很火 ,主要是因为Retrofit使用方便并且解耦强 , 而Rxjava可以自由的切换线程 ,不用我们访问网络创建子线程,得到数据在转换到主线程

下面是我封装的一个简单的WebService+Rxjava的代码 ,如果我意见或问题 请大家留言,一起成长

package com.example.qikais.myapplication.webservice;import com.example.qikais.myapplication.retfiter.ProgressSubscriber;import com.google.gson.Gson;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 java.io.IOException;import java.util.Map;import rx.Observable;import rx.Subscriber;import rx.android.schedulers.AndroidSchedulers;import rx.functions.Action0;import rx.schedulers.Schedulers;/** * Created by qikais on 2017/7/31. */public class WebService<T> {    private boolean isHttps = false;    public void getRxjava(final Class clazz , final String NameSpace, final String MethodName,                          final String URL , final Map<String ,String> map, final ProgressSubscriber<T> subscriber){        //1.通过Observable.create创建一个被观察者对象  再重写call通知观察者        Observable.create(new Observable.OnSubscribe<T>() {            @Override            public void call(Subscriber<? super T> subscriber) {                try {                    subscriber.onNext((T) new Gson().fromJson(getData(NameSpace, MethodName, URL ,map),clazz));                } catch (Exception e) {                    subscriber.onError(e);                }                subscriber.onCompleted();            }            //2.设置观察者和被观察者执行的线程    }).subscribeOn(Schedulers.io())                .unsubscribeOn(Schedulers.io())                .observeOn(AndroidSchedulers.mainThread())                .doOnSubscribe(new Action0() {                    @Override                    public void call() {                        subscriber.showProgressDialog();                    }                    //3.观察者被观察者关联                }).subscribe(subscriber);    }    //访问网络获取数据    private String getData(String NameSpace, String MethodName, String URL , Map<String , String> map) throws IOException, XmlPullParserException {        if(isHttps){            _FakeX509TrustManager.allowAllSSL();        }        //1.创建SoapObject 入参  命名空间  WebService服务端的具体方法名        SoapObject soapObject = new SoapObject(NameSpace, MethodName);        //2.通过SoapObject的addProperty方法添加参数        for (Map.Entry<String, String> entry : map.entrySet()) {            soapObject.addProperty(entry.getKey(), entry.getValue());        }        //3.创建SoapSerializationEnvelope对象,传入SOAP协议版本号  默认是VER11  主要还是看service        SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);        envelope.dotNet = false;   //true表示服务器获取入参按添加的顺序        envelope.setOutputSoapObject(soapObject);        //4.创建HttpTransportSE真正访问网络获取数据的对象 传入URL        //AndroidHttpTransport HttpTransportS的子类 多需要传入一个连接时间 不过这个方法已经过期了//        HttpTransportSE httpsE = new HttpTransportSE(URL);        AndroidHttpTransport httpsE=new AndroidHttpTransport(URL,30000);        httpsE.debug = false;    //是否是调试模式S        //5.HttpTransportS调用call方法发起数据 传入    命名空间/方法名  ,  SoapSerializationEnvelope对象   ,  设置额外请求头        //访问成功后 自动讲数据存储到 SoapSerializationEnvelope的bodyIn里面了        httpsE.call(NameSpace + "/" + MethodName, envelope, null);        return envelope.getResponse().toString();//        envelope.bodyIn//        logonResponse{logonReturn={"admin":false,"bureauID":null,"bureauName":"3440102","bureauTitle":null,"css":"default","departmentID":null,"departmentName":"0000073940","departmentTitle":null,"deskStyle":"default","groupID":null,"institutionID":null,"institutionName":null,"institutionPath":"","institutionTitle":null,"kind":4,"loginName":"yyy","logonTime":"2017-07-29T18:49:33","machineIP":"172.20.81.67","machineName":"172.20.81.67","modifyTime":"2017-04-24T09:09:08","modifyUserID":"{CD198DD6-82FD-5BBB-010B-519BD766787A}","personID":null,"personName":null,"personTitle":null,"sectionID":null,"sectionName":null,"sectionTitle":null,"user":{"ID":"{CD198DD6-82FD-5BBB-010B-519BD766787A}","alarmStyle":"complain.mp3","autoShowMessage":false,"bureauID":null,"bureauName":"3440102","bureauTitle":null,"css":"default","departmentID":null,"departmentName":"0000073940","departmentTitle":null,"deskStyle":"default","email":"glm19850719@163.com","email2":"aaaa@asf.com","endTime":null,"expired":false,"grantee":null,"grantors":null,"groupID":null,"index":0,"institutionID":null,"institutionName":null,"institutionTitle":null,"ipLimit":null,"macAddress":null,"mobile":"13800138001","modifyID":"{CD198DD6-82FD-5BBB-010B-519BD766787A}","modifyTime":"2017-04-24T09:09:08","name":"YYY","office1":"11","office2":"1111","personID":null,"personName":null,"personTitle":null,"realm":"","sectionID":null,"sectionName":null,"sectionTitle":null,"startTime":null,"title":"营业员","virtualNumber":"851997"},"userID":"{CD198DD6-82FD-5BBB-010B-519BD766787A}","userTitle":"营业员","userTitleEx":"营业员","username":"YYY","usernameEx":"YYY","validLogon":true,"webPath":"http:\/\/172.19.188.189:6070\/web"}; }//        envelope.getResponse()//        {"admin":false,"bureauID":null,"bureauName":"3440102","bureauTitle":null,"css":"default","departmentID":null,"departmentName":"0000073940","departmentTitle":null,"deskStyle":"default","groupID":null,"institutionID":null,"institutionName":null,"institutionPath":"","institutionTitle":null,"kind":4,"loginName":"yyy","logonTime":"2017-07-29T18:49:33","machineIP":"172.20.81.67","machineName":"172.20.81.67","modifyTime":"2017-04-24T09:09:08","modifyUserID":"{CD198DD6-82FD-5BBB-010B-519BD766787A}","personID":null,"personName":null,"personTitle":null,"sectionID":null,"sectionName":null,"sectionTitle":null,"user":{"ID":"{CD198DD6-82FD-5BBB-010B-519BD766787A}","alarmStyle":"complain.mp3","autoShowMessage":false,"bureauID":null,"bureauName":"3440102","bureauTitle":null,"css":"default","departmentID":null,"departmentName":"0000073940","departmentTitle":null,"deskStyle":"default","email":"glm19850719@163.com","email2":"aaaa@asf.com","endTime":null,"expired":false,"grantee":null,"grantors":null,"groupID":null,"index":0,"institutionID":null,"institutionName":null,"institutionTitle":null,"ipLimit":null,"macAddress":null,"mobile":"13800138001","modifyID":"{CD198DD6-82FD-5BBB-010B-519BD766787A}","modifyTime":"2017-04-24T09:09:08","name":"YYY","office1":"11","office2":"1111","personID":null,"personName":null,"personTitle":null,"realm":"","sectionID":null,"sectionName":null,"sectionTitle":null,"startTime":null,"title":"营业员","virtualNumber":"851997"},"userID":"{CD198DD6-82FD-5BBB-010B-519BD766787A}","userTitle":"营业员","userTitleEx":"营业员","username":"YYY","usernameEx":"YYY","validLogon":true,"webPath":"http:\/\/172.19.188.189:6070\/web"}    }}

里面的Subsceiber观察者我写了个带加载动画和异常处理的功能

package com.example.qikais.myapplication.retfiter;import android.content.Context;import com.example.dome.MyApplition;import com.example.dome.retfiter.ProgressCancelListener;import com.example.qikais.myapplication.retfiter.exception.ApiException;import com.example.qikais.myapplication.utils.NetworkUtils;import com.example.qikais.myapplication.view.widget.SimpleLoadDialog;import rx.Subscriber;public  abstract class ProgressSubscriber<T> extends Subscriber<T> implements ProgressCancelListener{    private SimpleLoadDialog dialogHandler;    public ProgressSubscriber(Context context) {        dialogHandler = new SimpleLoadDialog(context,this,true);    }    @Override    public void onCompleted() {        dismissProgressDialog();    }    /** 显示Dialog*/    public void showProgressDialog(){        if (dialogHandler != null) {            dialogHandler.obtainMessage(SimpleLoadDialog.SHOW_PROGRESS_DIALOG).sendToTarget();            dialogHandler.show();        }    }    @Override    public void onNext(T t) {        _onNext(t);    }    /** 隐藏Dialog*/    private void dismissProgressDialog(){        if (dialogHandler != null) {            dialogHandler.obtainMessage(SimpleLoadDialog.DISMISS_PROGRESS_DIALOG).sendToTarget();            dialogHandler.dismiss();            dialogHandler=null;        }    }    @Override    public void onError(Throwable e) {        e.printStackTrace();        if (NetworkUtils.checkNetwork(MyApplition.appcontext)) {            _onError("网络不可用");        } else if (e instanceof ApiException) {            _onError(e.getMessage());        } else {            _onError("请求失败,请稍后再试...");        }        dismissProgressDialog();    }    @Override    public void onCancelProgress() {        if (!this.isUnsubscribed()) {            System.out.println("销毁");            this.unsubscribe();        }    }    protected abstract void _onNext(T t);    protected abstract void _onError(String message);}