1:Retrofit 2 是一个网络框架 底层是OKHTTP 一个公司出的 square
2:Retrofit 2可以跟 Rxjava交互
3:Rxjava是什么东西 相当于一个网络处理的调味品 基于java 完全异步,基于观察者模式
4:观察者模式
Observer(观察者) 和Observable(被观察者)
如何使用
1:导入各种依赖
2:写一个工具类用来初始化OKHTTP和Retrofit
3:声明一个接口能用注解去请求网络APIService 通过Retrofit里面一个create(xxxApi.class)
这个是在项目的build.grade里面直接粘过去就OK
ext {
// Sdk and tools
minSdkVersion = 19
targetSdkVersion = 26
compileSdkVersion = 26
buildToolsVersion = '26.0.2'
//support版本
supportVersion = '27.1.0'
constraintLayout = '1.0.2'
junit = '4.12'
testRunner = '1.0.1'
espressoCore = '3.0.1'
interceptor = "3.11.0"
retrofit = '2.3.0'
converterGson = '2.3.0'
rxandroid = '1.2.1'
rxjava = '1.3.0'
rxbus = '1.0.6'
adapterRxjava = '2.0.2'
}
implementation "com.squareup.okhttp3:logging-interceptor:$rootProject.interceptor"
implementation "com.squareup.retrofit2:retrofit:$rootProject.retrofit"
implementation "com.squareup.retrofit2:converter-gson:$rootProject.converterGson"
implementation "io.reactivex:rxandroid:$rootProject.rxandroid"
implementation "io.reactivex:rxjava:$rootProject.rxjava"
implementation "com.hwangjr.rxbus:rxbus:$rootProject.rxbus"
implementation "com.squareup.retrofit2:adapter-rxjava:$rootProject.adapterRxjava"
implementation 'com.jakewharton:butterknife:8.8.1'
annotationProcessor 'com.jakewharton:butterknife-compiler:8.8.1'
存放接口的类
//用来存放所有接口
public class Contacts {
//总接口前缀
public static final String BASE_URL = "http://www.zhaoapi.cn/";
//登陆
public static final String USER_LOGIN = "user/login";
//用户信息
public static final String USER_INFO = "user/getUserInfo";
//上传图片
public static final String UP_LOAD_IMAGE = "file/upload";
}
处理接口
/**
* 他用来处理接口
*/
public interface MyApiService {
//Retrofit + Rxjava
@GET
Observable get(@Url String url,@QueryMap Map map);
//Observable 被观察者
@POST
Observable post(@Url String url, @QueryMap Map map);
//这是Retrofit的使用
@GET
Call get();
}
接下来介绍工具类,注意包不要导错
import android.os.Environment;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import rx.Observer;
import rx.Scheduler;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
import soexample.umeng.com.retrofitokhttpdemo.Contacts;
public class RetrofitUtils {
private MyApiService myApiService;
private RetrofitUtils() {
HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient okHttpClient = new OkHttpClient.Builder()
.readTimeout(20, TimeUnit.SECONDS)
.connectTimeout(20, TimeUnit.SECONDS)
.writeTimeout(20, TimeUnit.SECONDS)
.addInterceptor(loggingInterceptor)
//配置此客户端,以便在遇到连接问题时重试或不重试。默认情况下,
//*该客户端从以下问题中悄悄恢复
.retryOnConnectionFailure(true)
.build();
//初始化Retrofit 并结合各种操作
Retrofit retrofit = new Retrofit.Builder()
//结合Gson解析
.addConverterFactory(GsonConverterFactory.create())
//结合Rxjava
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.baseUrl(Contacts.BASE_URL)
.client(okHttpClient)
.build();
//通过Retrofit创建完 这个ApiService 就可以调用方法了
myApiService = retrofit.create(MyApiService.class);
}
public static RetrofitUtils getInstance() {
return RetroHolder.retro;
}
private static class RetroHolder {
private static final RetrofitUtils retro = new RetrofitUtils();
}
//封装Get方式 这里面采用构造者模式 就是调用这个方法有返回自己本身这个对象
public RetrofitUtils get(String url, Map map) {
//这个订阅事件(处理网络请求)放生那个线程
//Schedulers 线程调度器
myApiService.get(url, map).subscribeOn(Schedulers.io())//io就是子线程
//在主线程调用
.observeOn(AndroidSchedulers.mainThread())
.subscribe(observer);
return RetrofitUtils.getInstance();
}
/**
* 表单post请求
*/
public RetrofitUtils post(String url, Map map) {
if (map == null) {
map = new HashMap<>();
}
myApiService.post(url, map)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(observer);
return RetrofitUtils.getInstance();
}
//子类使用
private Subscriber subscriber = new Subscriber() {
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable e) {
}
@Override
public void onNext(ResponseBody responseBody) {
}
};
//重写一个观察者对象
private Observer observer = new Observer() {
@Override
public void onCompleted() {
}
//网络处理失败
@Override
public void onError(Throwable e) {
if (httpListener != null) {
httpListener.onError(e.getMessage());
}
}
//网络处理成功
@Override
public void onNext(ResponseBody responseBody) {
if (httpListener != null) {
try {
httpListener.onSuccess(responseBody.string());
} catch (IOException e) {
e.printStackTrace();
}
}
}
};
public interface HttpListener {
void onSuccess(String jsonStr);
void onError(String error);
}
private HttpListener httpListener;
public void setHttpListener(HttpListener listener) {
this.httpListener = listener;
}
}
动态权限
private void checkPermission(int type) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.INTERNET) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.INTERNET}, type);
} else {
startRequest(type);
}
} else {
startRequest(type);
}
}
成功之后的调用
@Override
public void onSuccess(Object data) {
//因为是复用一个处理的 用java的一个关键字instanceof处理一下即可
if (data instanceof LoginBean) {
Toast.makeText(this, ((LoginBean) data).getMsg(), Toast.LENGTH_SHORT).show();
} else if (data instanceof UserInfoBean) {
UserInfoBean userIfo = (UserInfoBean) data;
Toast.makeText(this, userIfo.getMsg(), Toast.LENGTH_SHORT).show();
}
}
5、让我们继续畅游在知识的海洋,一起去探究retrofit实现断点续传结合后台服务下载的魅力