1北救、添加依賴庫
添加retrofit荐操、okhttp、rxjava珍策、rxandroid托启、gson依賴庫。
implementation'com.squareup.retrofit2:retrofit:2.0.0'
implementation'com.squareup.retrofit2:converter-gson:2.0.0'
api'com.google.code.gson:gson:2.6.1'
api'com.squareup.okhttp3:okhttp:3.2.0'
api'com.squareup.retrofit2:adapter-rxjava:2.0.0'
implementation'io.reactivex:rxjava:1.1.0'
implementation'io.reactivex:rxandroid:1.1.0'
api'com.squareup.okhttp3:logging-interceptor:3.2.0'
2攘宙、創(chuàng)建用于描述網(wǎng)絡(luò)請求的接口
用動態(tài)代理動態(tài)的將該接口的注解翻譯成一個http請求屯耸,最好在執(zhí)行http請求。
接口中每個方法的參數(shù)都有使用注解標注蹭劈,否則會報錯疗绣。
public interface ApiService {
????? @POST("login.html")
????? Call<JsonObject> login(@Body LoginParam param);
}
注解類型
網(wǎng)絡(luò)請求的方法:@POST? @GET? @PUT? @DELETE? @PATH @HEAD @OPTIONS @HTTP
標記類:@FormUrlEncoded? @Multipart? @Streaming
網(wǎng)絡(luò)請求參數(shù):@Header @headers @URL @Body @Path @Field @FieldMap
???????????????????????? @Part @PartMap? @Query @QueryMap
網(wǎng)絡(luò)請求的完整Url = 創(chuàng)建Retrofit實例時通過baseUrl()設(shè)置+網(wǎng)絡(luò)請求接口的注解設(shè)置(@POST括號后面)。
@FormUrlEncoded 表示發(fā)送form-encoded的數(shù)據(jù)铺韧,每個鍵值對需要用Field來注解鍵名多矮,隨后的對象需要提供值。
@Multipart 表示發(fā)送form-encoded的數(shù)據(jù)(適用于文件上傳的場景)哈打,每個鍵值對用@Part來注解鍵名工窍,隨后的對象需要提供值。
RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), filePath);
MultipartBody.Part part = MultipartBody.Part.createFormData("imgFile", filePath.getName(), requestFile);
@POST("login.html")
@Multipart
Call uploadFile(@Part? MultipartBody.Part? part);
3前酿、創(chuàng)建Retrofit實例
???? Retrofit retrofit =new Retrofit.Builder() ;
???? retrofit.baseUrl("https://www.sojson.com/open/api/weather/") ;?
???? retrofit.addConverterFactory(GsonConverterFactory.create()) ;
???? retrofit.addCallAdapterFactory(RxJavaCallAdapterFactory.create());
?? //設(shè)置請求Https或Http
???? retrofit.client(USE_HTTPS ? generateHttpsClient(context) : getHttpClient());
??? /*** 使用http方式請求網(wǎng)絡(luò) */
?? @NonNull
??? private OkHttpClientgetHttpClient() {
????????? okHttpClient.connectTimeout(10 , TimeUnit.SECONDS);
????????? return okHttpClient.build();
??? }
??? /**https*/ 請求
???? private OkHttpClientgenerateHttpsClient(Context context) {
???????????? try {
???????????????? SSLSocketFactory socketFactory =new NoSSLv3SocketFactory(getSSLConfig(context,???????? R.raw.smartcampus).getSocketFactory());
???????????????? okHttpClient.sslSocketFactory(socketFactory);
?????????????? }catch (IOException e) {
????????????????????? e.printStackTrace();
????????????? }catch (CertificateException e) {
????????????????????? e.printStackTrace();
??????????? ? }catch (NoSuchAlgorithmException e) {
????????????????????? e.printStackTrace();
?????????? ? }catch (KeyStoreException e) {
????????????????????? e.printStackTrace();
???????????? }catch (KeyManagementException e) {
????????????????????? e.printStackTrace();
????????????? }
??????????? return okHttpClient.build();
???? }
4患雏、創(chuàng)建請求接口實例
??? ApiService apiService = retrofit.build().create(ApiService.class);
5、發(fā)送網(wǎng)絡(luò)請求
??? apiService.login(param).enqueue(new Callback() {
??????????? @Override
???????????? public void onResponse(Call call, Response response) {
????????????????????? if (response.isSuccessful()) {
?????????????????????????? LogUtil.e("member", "body==" + response.body().toString());
?????????????????????????? int code = response.body().get(ConfigUtil.CODE).getAsInt();
????????????????????????? String message = response.body().get(ConfigUtil.MSG).getAsString();
?????????????????????????? if (code ==200) {
??????????????????????????????? JsonObject jsonObject = response.body().getAsJsonObject(ConfigUtil.BODY);
????????????????????????? ? }else {
?????????????????????????????? ToastUtils.showToast(LoginActivity.this, message);
???????????????????????? }
?????????????????? }
????????????? dialog.dismiss();
????????????? }
?????? @Override
??????? public void onFailure(Call call, Throwable t) {
???????????????? dialog.dismiss();
???????? }
?? });
RxJava
RxJava是基于事件流罢维,實現(xiàn)異步操作的庫淹仑。
作用:實現(xiàn)異步操作
特點:邏輯簡潔、實現(xiàn)優(yōu)雅(基于事件流的鏈式調(diào)用)肺孵、使用簡單
原理:基于一種擴展的觀察者模式
被觀察者(Observable)通過訂閱(Subscribe)按順序發(fā)送事件(Event)給觀察者(Observer),觀察者按順序接收事件并對應(yīng)的相應(yīng)動作匀借。