Rxjava与Retrofit的结合:二

Https网络请求,条件是:传入的值为json格式的内容:

这个需要到了okhttpClient对象

创建传入值的对象,然后通过Gson转换成json如:
package ipos.crg.com.recycledemo;

/**
 * Description:
 * Date       : 2018/8/1 17:53
 */

public class DeviceInfo {
    private String bicycle;
    private String        deviceMac;
    private GameBean      game;
    private String        gameFlag;
    private String        message;
    private String        sportFlag;
    private String        state;
    private TreadmillBean treadmill;
    private String        username;
    public DeviceInfo(String bicycle, String deviceMac, GameBean game, String gameFlag, String message, String sportFlag, String state, TreadmillBean treadmill, String username) {
        this.bicycle = bicycle;
        this.deviceMac = deviceMac;
        this.game = game;
        this.gameFlag = gameFlag;
        this.message = message;
        this.sportFlag = sportFlag;
        this.state = state;
        this.treadmill = treadmill;
        this.username = username;
    }


    public String getBicycle() {
        return bicycle;
    }

    public void setBicycle(String bicycle) {
        this.bicycle = bicycle;
    }

    public String getDeviceMac() {
        return deviceMac;
    }

    public void setDeviceMac(String deviceMac) {
        this.deviceMac = deviceMac;
    }

    public GameBean getGame() {
        return game;
    }

    public void setGame(GameBean game) {
        this.game = game;
    }

    public String getGameFlag() {
        return gameFlag;
    }

    public void setGameFlag(String gameFlag) {
        this.gameFlag = gameFlag;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public String getSportFlag() {
        return sportFlag;
    }

    public void setSportFlag(String sportFlag) {
        this.sportFlag = sportFlag;
    }

    public String getState() {
        return state;
    }

    public void setState(String state) {
        this.state = state;
    }

    public TreadmillBean getTreadmill() {
        return treadmill;
    }

    public void setTreadmill(TreadmillBean treadmill) {
        this.treadmill = treadmill;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public static class GameBean {
        private String gameid;
        private String name;
        private String rank;
        private String score;

        public GameBean() {
        }

        public GameBean(String gameid, String name, String rank, String score) {
            this.gameid = gameid;
            this.name = name;
            this.rank = rank;
            this.score = score;
        }

        public String getGameid() {
            return gameid;
        }

        public void setGameid(String gameid) {
            this.gameid = gameid;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getRank() {
            return rank;
        }

        public void setRank(String rank) {
            this.rank = rank;
        }

        public String getScore() {
            return score;
        }

        public void setScore(String score) {
            this.score = score;
        }
    }

    public static class TreadmillBean {
        private String calorie;
        private String distance;
        private String heartRate;
        private String steps;
        private String time;

        public TreadmillBean(String calorie, String distance, String heartRate, String steps, String time) {
            this.calorie = calorie;
            this.distance = distance;
            this.heartRate = heartRate;
            this.steps = steps;
            this.time = time;
        }

        public String getCalorie() {
            return calorie;
        }

        public void setCalorie(String calorie) {
            this.calorie = calorie;
        }

        public String getDistance() {
            return distance;
        }

        public void setDistance(String distance) {
            this.distance = distance;
        }

        public String getHeartRate() {
            return heartRate;
        }

        public void setHeartRate(String heartRate) {
            this.heartRate = heartRate;
        }

        public String getSteps() {
            return steps;
        }

        public void setSteps(String steps) {
            this.steps = steps;
        }

        public String getTime() {
            return time;
        }

        public void setTime(String time) {
            this.time = time;
        }
    }
}
创建返回数据对象:
package ipos.crg.com.recycledemo;

/**
 * Description:
 * Date       : 2018/8/1 18:25
 */

public class Test3ResponseInfo {
    private String isSuccess;
    private String message;

    public Test3ResponseInfo() {
    }

    public Test3ResponseInfo(String isSuccess, String message) {
        this.isSuccess = isSuccess;
        this.message = message;
    }

    public String getIsSuccess() {
        return isSuccess;
    }

    public void setIsSuccess(String isSuccess) {
        this.isSuccess = isSuccess;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    @Override
    public String toString() {
        return "Test3ResponseInfo{" +
                "isSuccess='" + isSuccess + '\'' +
                ", message='" + message + '\'' +
                '}';
    }
}

创建接口
public interface Test3Api {
    //需要添加头
    @Headers({"Content-Type: application/json","Accept: application/json"})
    @POST("start/")
    Observable getTest3(@Body RequestBody info);
}
编写代码
a.获取okhttpClient对象
 try {
            sslctxt = SSLContext.getInstance("TLS");
            TrustAllManager myX509TrustManager = new TrustAllManager(getX509Certificate(this));
            sslctxt.init(null, new TrustManager[] { myX509TrustManager },new java.security.SecureRandom());
            OkHttpClient.Builder builder = new OkHttpClient.Builder();
            builder.sslSocketFactory(sslctxt.getSocketFactory());
            builder.hostnameVerifier(new TrustAllHostnameVerifier());
            mHttpClient = builder.build();
        } catch (Exception e) {
            e.printStackTrace();
        }

TrustAllManager类

public class TrustAllManager implements X509TrustManager {
    X509Certificate mX509Certificate;
    
    
    public TrustAllManager(X509Certificate mX509Certificate) {
        this.mX509Certificate = mX509Certificate;
    }
 
    @Override
    public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {

    }

    @Override
    public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        for (X509Certificate certificate:chain){
            certificate.checkValidity();
            try {
                certificate.verify(mX509Certificate.getPublicKey());
            } catch (Exception e) {
                e.printStackTrace();
            } 
        }
    }

    @Override
    public X509Certificate[] getAcceptedIssuers() {
        return new X509Certificate[0];
    }
}

方法getX509Certificate():

 private X509Certificate getX509Certificate(Context context) {
        X509Certificate certificate = null ;
        try {
            InputStream in = context.getAssets().open("wl.csr");
            CertificateFactory instance = CertificateFactory.getInstance("X.509");
            certificate = (X509Certificate) instance.generateCertificate(in);

        } catch (Exception e) {
            // TODO: handle exception
        }
        return certificate;

    }

TrustAllHostnameVerifier 类

public class TrustAllHostnameVerifier implements HostnameVerifier {
    @Override
    public boolean verify(String hostname, SSLSession session) {
        Log.e("mmm","hostname = " + hostname);
        return true;
    }
}
b.转换对象为json
Gson gson = new Gson();
DeviceInfo info = new DeviceInfo("", "38:a2:8c:ee:84:7b", new DeviceInfo.GameBean(), "0", "", "1", "OFF", new DeviceInfo.TreadmillBean("4", "5", "100", "100", "10"), "shiluxia");

String json = gson.toJson(info);
RequestBody requestBody = RequestBody.create(MediaType.parse("application/json;charset=utf-8"), json);
c.创建Retrofit对象
  Retrofit retrofit = new Retrofit.Builder()
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .baseUrl("xxxxxxxx")
                .client(mHttpClient)
                .build();
d.创建网络请求实例:
 Test3Api test3Api = retrofit.create(Test3Api.class);
        Observable test3 = test3Api.getTest3(requestBody);
        test3.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1() {
                    @Override
                    public void call(Test3ResponseInfo test3ResponseInfo) {
                        Log.e("www", "ResponseInfo = " + test3ResponseInfo.toString());
                    }
                });

subscribeOn(): 指定 subscribe() 所发生的线程,即 Observable.OnSubscribe 被激活时所处的线程。或者叫做事件产生的线程。
observeOn(): 指定 Subscriber 所运行在的线程。或者叫做事件消费的线程。

你可能感兴趣的:(Rxjava与Retrofit的结合:二)