先导入依赖:
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17//okhttp3 implementation "com.squareup.okhttp3:okhttp:5.0.0-alpha.2" //okhttp-utils implementation 'com.qianwen:okhttp-utils:+' //okhttp-utils implementation 'com.lzy.net:okhttputils:+' //可以单独使用,不需要依赖下方的扩展包 //retrofit2 implementation "com.squareup.retrofit2:retrofit:2.9.0" implementation "com.squareup.retrofit2:converter-gson:2.9.0" implementation "com.squareup.retrofit2:adapter-rxjava2:2.9.0" implementation 'com.squareup.retrofit2:converter-scalars:2.9.0' //rxandroid implementation 'io.reactivex.rxjava2:rxandroid:2.1.1' //dagger-android implementation 'com.google.dagger:dagger:2.30.1' annotationProcessor 'com.google.dagger:dagger-compiler:2.30.1'
在包名下建:
复制代码
1remotedata
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21import com.zhipuchina.heavymetal.remotedata.systemapi.SystemApiService; import com.zhipuchina.heavymetal.remotedata.systemapi.SystemApiServiceModule; import com.zhipuchina.heavymetal.ui.home.HomeActivity; import com.zhipuchina.heavymetal.ui.home.SpecimenDetectionFragment; import javax.inject.Singleton; import dagger.Component; @Singleton @Component(modules = {SystemApiServiceModule.class, SpModule.class}) public interface AppComponent { SystemApiService getSystemService(); //首页 void doInjectionMain(HomeActivity HomeActivity); //检测结果 void doInjectionMain(SpecimenDetectionFragment SpecimenDetectionFragment); }
复制代码
1
2
3
4
5
6
7package com.zhipuchina.heavymetal.remotedata; public class BaseApiModule { public static final String SYSTEM_URL = "https://*********"; //正 }
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42package com.zhipuchina.heavymetal.remotedata; import com.zhipuchina.heavymetal.mobile.system.EquipmentMessage; import com.zhipuchina.heavymetal.utils.data.EquipmentMessageUtils; import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.Set; import okhttp3.Interceptor; import okhttp3.Request; import okhttp3.Response; public class BaseInterceptor implements Interceptor { private Map<String, String> headers = new HashMap<>(); public BaseInterceptor() { } public BaseInterceptor(Map<String, String> headers) { this.headers = headers; } @Override public Response intercept(Chain chain) throws IOException { Request.Builder builder = chain.request() .newBuilder(); if (headers != null && headers.size() > 0) { Set<String> keys = headers.keySet(); for (String headerKey : keys) { builder.addHeader(headerKey, headers.get(headerKey)).build(); } } //请求信息 return chain.proceed(builder.build()); } }
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59package com.zhipuchina.heavymetal.remotedata; import com.blankj.utilcode.util.LogUtils; import com.blankj.utilcode.util.ToastUtils; import com.zhipuchina.heavymetal.mobile.ResultEntity; import io.reactivex.annotations.NonNull; import io.reactivex.observers.DisposableObserver; public abstract class InterceptObserver<T> extends DisposableObserver<ResultEntity> implements IObserver { @Override protected void onStart() { super.onStart(); } @Override public void onNext(@NonNull ResultEntity resultEntity) { if(resultEntity.getStatus() == 200){ onNextData(resultEntity); }else { onErrorNet(null,resultEntity.getMsg()); } } @Override public void onError(@NonNull Throwable e) { LogUtils.d(e.getMessage()); onErrorNet(null,e.getMessage()); } @Override public void onComplete() { onFinish(); } @Override public boolean isShowToast() { return true; } @Override public void onFinish() { LogUtils.d("onFinish"); } @Override public void onDataEmpty(String netMsg) { ToastUtils.showShort(netMsg); } @Override public void onNoData(String netMsg) { LogUtils.d(netMsg); } }
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40package com.zhipuchina.heavymetal.remotedata; import com.zhipuchina.heavymetal.mobile.ResultEntity; /** * @author zhengweijun * @date 2020/7/14 13:21 */ public interface IObserver { /** * 最终必回执行的 */ public void onFinish(); /** * 成功数据data */ void onNextData(ResultEntity resultEntity); /** * 暂无数据 * @param netMsg */ public void onNoData(String netMsg); /** * 错误网络 */ public abstract void onErrorNet(Throwable t, String netMsg); /** * 错误网络 */ public abstract void onDataEmpty( String netMsg); /** * 是否显示toast错误码的 */ public boolean isShowToast(); }
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22package com.zhipuchina.heavymetal.remotedata; import android.content.Context; import android.content.SharedPreferences; import dagger.Module; import dagger.Provides; @Module public class SpModule { Context appComponent; public SpModule(Context appComponent) { this.appComponent = appComponent; } @Provides SharedPreferences provideSp() { return appComponent.getSharedPreferences("ThreePigeonFlowWater", Context.MODE_PRIVATE); } }
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35package com.zhipuchina.heavymetal.remotedata; import androidx.annotation.NonNull; import androidx.lifecycle.ViewModel; import androidx.lifecycle.ViewModelProvider; import com.zhipuchina.heavymetal.remotedata.systemapi.SystemApiService; import com.zhipuchina.heavymetal.ui.home.HomeViewModel; import com.zhipuchina.heavymetal.ui.home.SpecimenDetectionViewModel; import javax.inject.Inject; public class ViewModelFactory implements ViewModelProvider.Factory { private SystemApiService apiCallInterface; @Inject public ViewModelFactory(SystemApiService apiCallInterface) { this.apiCallInterface = apiCallInterface; } @NonNull @Override public <T extends ViewModel> T create(@NonNull Class<T> modelClass) { if (modelClass.isAssignableFrom(SpecimenDetectionViewModel.class)) { return (T) new SpecimenDetectionViewModel(apiCallInterface); }else if (modelClass.isAssignableFrom(HomeViewModel.class)) { return (T) new HomeViewModel(apiCallInterface); } throw new IllegalArgumentException("Unknown class name"); } }
栏目:
复制代码
1systemapi
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36package com.zhipuchina.heavymetal.remotedata.systemapi; import com.zhipuchina.heavymetal.mobile.pihao.PiHaoYangPin; import com.zhipuchina.heavymetal.mobile.record.ResponseVersionInfo; import com.zhipuchina.heavymetal.mobile.DevCode; import com.zhipuchina.heavymetal.mobile.ResultEntity; import com.zhipuchina.heavymetal.mobile.record.HeavyMetalData; import com.zhipuchina.heavymetal.mobile.record.JsonRootBean; import com.zhipuchina.heavymetal.mobile.system.EquipmentMessage; import java.util.List; import java.util.Map; import io.reactivex.Observable; import retrofit2.http.Body; import retrofit2.http.GET; import retrofit2.http.HTTP; import retrofit2.http.Header; import retrofit2.http.Headers; import retrofit2.http.POST; import retrofit2.http.Path; import retrofit2.http.Query; import retrofit2.http.QueryMap; public interface SystemApiService { @POST("这里写不一样的接口") Observable<ResultEntity<Object>> getDevCode(@Header("Sign") String Sign, @Header("Time") long Time, @Body DevCode requestBody); }
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65package com.zhipuchina.heavymetal.remotedata.systemapi; import android.content.Context; import androidx.lifecycle.ViewModelProvider; import com.zhipuchina.heavymetal.remotedata.BaseApiModule; import com.zhipuchina.heavymetal.remotedata.BaseInterceptor; import com.zhipuchina.heavymetal.remotedata.ViewModelFactory; import com.zhipuchina.heavymetal.utils.HttpsUtils; import org.apache.http.conn.ssl.SSLSocketFactory; import javax.inject.Singleton; import dagger.Module; import dagger.Provides; import okhttp3.OkHttpClient; import retrofit2.Retrofit; import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory; import retrofit2.converter.gson.GsonConverterFactory; @Module public class SystemApiServiceModule extends BaseApiModule { private Context context; private Retrofit retrofit = null; public SystemApiServiceModule(Context context) { this.context = context.getApplicationContext(); } @Provides @Singleton public Retrofit provideRetrofit() { HttpsUtils.SSLParams sslParams = HttpsUtils.getSslSocketFactory(); OkHttpClient.Builder okHttpClientBuilder = new OkHttpClient.Builder(); okHttpClientBuilder.hostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); okHttpClientBuilder.addInterceptor(new BaseInterceptor()); okHttpClientBuilder.sslSocketFactory(sslParams.sSLSocketFactory, sslParams.trustManager); OkHttpClient client = okHttpClientBuilder.build(); Retrofit retrofit = new Retrofit.Builder() .client(client) .addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .baseUrl(SYSTEM_URL) .build(); return retrofit; } @Provides @Singleton SystemApiService getApiCallInterface(Retrofit retrofit) { return retrofit.create(SystemApiService.class); } @Provides @Singleton ViewModelProvider.Factory getViewModelFactory(SystemApiService myRepository) { return new ViewModelFactory(myRepository); } }
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186package com.zhipuchina.heavymetal.utils; import java.io.IOException; import java.io.InputStream; import java.security.KeyManagementException; import java.security.KeyStore; import java.security.NoSuchAlgorithmException; import java.security.cert.Certificate; import java.security.cert.CertificateException; import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.KeyManager; import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSession; import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.TrustManager; import javax.net.ssl.TrustManagerFactory; import javax.net.ssl.X509TrustManager; public class HttpsUtils { public static class SSLParams { public SSLSocketFactory sSLSocketFactory; public X509TrustManager trustManager; } public static SSLParams getSslSocketFactory() { return getSslSocketFactoryBase(null, null, null); } /** * https单向认证 * 可以额外配置信任服务端的证书策略,否则默认是按CA证书去验证的,若不是CA可信任的证书,则无法通过验证 */ public static SSLParams getSslSocketFactory(X509TrustManager trustManager) { return getSslSocketFactoryBase(trustManager, null, null); } /** * https单向认证 * 用含有服务端公钥的证书校验服务端证书 */ public static SSLParams getSslSocketFactory(InputStream... certificates) { return getSslSocketFactoryBase(null, null, null, certificates); } /** * https双向认证 * bksFile 和 password -> 客户端使用bks证书校验服务端证书 * certificates -> 用含有服务端公钥的证书校验服务端证书 */ public static SSLParams getSslSocketFactory(InputStream bksFile, String password, InputStream... certificates) { return getSslSocketFactoryBase(null, bksFile, password, certificates); } /** * https双向认证 * bksFile 和 password -> 客户端使用bks证书校验服务端证书 * X509TrustManager -> 如果需要自己校验,那么可以自己实现相关校验,如果不需要自己校验,那么传null即可 */ public static SSLParams getSslSocketFactory(InputStream bksFile, String password, X509TrustManager trustManager) { return getSslSocketFactoryBase(trustManager, bksFile, password); } private static SSLParams getSslSocketFactoryBase(X509TrustManager trustManager, InputStream bksFile, String password, InputStream... certificates) { SSLParams sslParams = new SSLParams(); try { KeyManager[] keyManagers = prepareKeyManager(bksFile, password); TrustManager[] trustManagers = prepareTrustManager(certificates); X509TrustManager manager; if (trustManager != null) { //优先使用用户自定义的TrustManager manager = trustManager; } else if (trustManagers != null) { //然后使用默认的TrustManager manager = chooseTrustManager(trustManagers); } else { //否则使用不安全的TrustManager manager = UnSafeTrustManager; } // 创建TLS类型的SSLContext对象, that uses our TrustManager SSLContext sslContext = SSLContext.getInstance("TLS"); // 用上面得到的trustManagers初始化SSLContext,这样sslContext就会信任keyStore中的证书 // 第一个参数是授权的密钥管理器,用来授权验证,比如授权自签名的证书验证。第二个是被授权的证书管理器,用来验证服务器端的证书 sslContext.init(keyManagers, new TrustManager[]{manager}, null); // 通过sslContext获取SSLSocketFactory对象 sslParams.sSLSocketFactory = sslContext.getSocketFactory(); sslParams.trustManager = manager; return sslParams; } catch (NoSuchAlgorithmException e) { throw new AssertionError(e); } catch (KeyManagementException e) { throw new AssertionError(e); } } private static KeyManager[] prepareKeyManager(InputStream bksFile, String password) { try { if (bksFile == null || password == null) return null; KeyStore clientKeyStore = KeyStore.getInstance("BKS"); clientKeyStore.load(bksFile, password.toCharArray()); KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); kmf.init(clientKeyStore, password.toCharArray()); return kmf.getKeyManagers(); } catch (Exception e) { e.printStackTrace(); } return null; } private static TrustManager[] prepareTrustManager(InputStream... certificates) { if (certificates == null || certificates.length <= 0) return null; try { CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); // 创建一个默认类型的KeyStore,存储我们信任的证书 KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); keyStore.load(null); int index = 0; for (InputStream certStream : certificates) { String certificateAlias = Integer.toString(index++); // 证书工厂根据证书文件的流生成证书 cert Certificate cert = certificateFactory.generateCertificate(certStream); // 将 cert 作为可信证书放入到keyStore中 keyStore.setCertificateEntry(certificateAlias, cert); try { if (certStream != null) certStream.close(); } catch (IOException e) { e.printStackTrace(); } } //我们创建一个默认类型的TrustManagerFactory TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); //用我们之前的keyStore实例初始化TrustManagerFactory,这样tmf就会信任keyStore中的证书 tmf.init(keyStore); //通过tmf获取TrustManager数组,TrustManager也会信任keyStore中的证书 return tmf.getTrustManagers(); } catch (Exception e) { e.printStackTrace(); } return null; } private static X509TrustManager chooseTrustManager(TrustManager[] trustManagers) { for (TrustManager trustManager : trustManagers) { if (trustManager instanceof X509TrustManager) { return (X509TrustManager) trustManager; } } return null; } /** * 为了解决客户端不信任服务器数字证书的问题,网络上大部分的解决方案都是让客户端不对证书做任何检查, * 这是一种有很大安全漏洞的办法 */ public static X509TrustManager UnSafeTrustManager = new X509TrustManager() { @Override public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { } @Override public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { } @Override public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[]{}; } }; /** * 此类是用于主机名验证的基接口。 在握手期间,如果 URL 的主机名和服务器的标识主机名不匹配, * 则验证机制可以回调此接口的实现程序来确定是否应该允许此连接。策略可以是基于证书的或依赖于其他验证方案。 * 当验证 URL 主机名使用的默认规则失败时使用这些回调。如果主机名是可接受的,则返回 true */ public static HostnameVerifier UnSafeHostnameVerifier = new HostnameVerifier() { @Override public boolean verify(String hostname, SSLSession session) { return true; } }; }
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16这样使用即可 /** * retrofit2框架 */ private AppComponent appComponent; public AppComponent getAppComponent() {return appComponent; } /** * retrofit2框架 */ private void initiRetrofit2(){ appComponent = DaggerAppComponent.builder().systemApiServiceModule(new SystemApiServiceModule(this)).spModule(new SpModule(this)).build(); }
这样使用即可完成
最后
以上就是粗犷发箍最近收集整理的关于android MVVM+retrofit2+dagger的全部内容,更多相关android内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复