首先还是导依赖
//retrofit
implementation 'com.squareup.retrofit2:retrofit:2.5.0'
implementation 'com.squareup.retrofit2:converter-gson:2.0.2'
implementation 'com.squareup.okhttp3:logging-interceptor:3.6.0'
implementation 'io.reactivex:rxandroid:1.2.1'
implementation 'io.reactivex:rxjava:1.3.0'
implementation 'com.hwangjr.rxbus:rxbus:1.0.6'
implementation 'com.squareup.retrofit2:adapter-rxjava:2.0.2'
第二步添加网络权限了
第三步呢定义接口了(观察者模式,设请求方式)
/*Time:2019/5/15
*Author:zhaozhiwei
*Description:
*/
public interface IApiService {
/**
* GET请求
*/
@GET //ResponseBody是ok3提供的被观察者返回的对象
Observable getBannerShow(@Url String url);
/**
* get请求Header入参
*/
@GET
Observable getHeader(@Url String url, @Header("userId") String userid, @Header("sessionId") String sessionId);
/**
* 登陆
* @param phone
* @param pwd
* 观察者模式
*/
@FormUrlEncoded //这个加上有啥用,为什么不加这个会崩溃 @Field parameters can only be used with form encoding.
@POST
Observable getPostShow(@Url String url, @FieldMap Map map);
}
接下来此类封装了整GET、POST的请求方法,用的时候通过接口回调的方式调用
/*Time:2019/5/15
*Author:zhaozhiwei
*Description:
*/
public class RetrofitManager {
private IApiService iApiService;
private Retrofit mRetrofit;
private RetrofitManager(){
initRetrofit();
}
//静态内部类单例
private static class oKHPMH{
public static RetrofitManager instance = new RetrofitManager();
}
public static RetrofitManager getInstance(){
return oKHPMH.instance;
}
//网络判断
public boolean isNetWorkConneted(Context context){
if (context!=null){
ConnectivityManager systemService = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = systemService.getActiveNetworkInfo();
if (networkInfo!=null){
return networkInfo.isAvailable();
}
}
return false;
}
//初始化fit
private void initRetrofit() {
//拦截器
HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient.Builder builder = new OkHttpClient.Builder()
.addInterceptor(loggingInterceptor)//添加日志
.connectTimeout(10, TimeUnit.SECONDS)
.readTimeout(10,TimeUnit.SECONDS)
.writeTimeout(10,TimeUnit.SECONDS)
.retryOnConnectionFailure(true);
OkHttpClient client = builder.build();
//Retrofit的创建
mRetrofit = new Retrofit.Builder()
//添加Rxjava工厂
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.baseUrl("http://172.17.8.100/")
.addConverterFactory(GsonConverterFactory.create())
.client(client)
.build();
iApiService = mRetrofit.create(IApiService.class);
}
//Get请求
public void doGet(String url, final ICallBack callback){
iApiService.getBannerShow(url)
//被观察者执行在哪个线程,这里面执行在io线程,io线程是一个子线程
.subscribeOn(Schedulers.io())
//最终完成后结果返回到哪个线程,mainThread代表主线
.observeOn(AndroidSchedulers.mainThread())
.subscribe(getObsetver(callback));
}
//POst请求
public void doPost(String url, Map params,ICallBack callBack){
//一定要判空,如果是空,创建一个实例就可以了
if (params == null){
params = new HashMap<>();
}
iApiService.getPostShow(url,params)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(getObsetver(callBack));
}
//拿结果
private Observer getObsetver(final ICallBack callBack){
//Rxjava
Observer observer = new Observer(){
@Override
public void onCompleted() {
//完成,所有事件全部完成才会执行
}
@Override
public void onError(Throwable e) {
//任何一个事件报错后执行
if (callBack!=null){
callBack.failureData(e.getMessage());
Log.i("AAA", e.getMessage());
}
}
@Override
public void onNext(ResponseBody responseBody) {
//单一事件完成后执行
//请求完成,会走onNext
//这里面的请求完成,不代表服务器告诉我们请求成功
//200 404 503这些都代表请求完成,有结果,中间没报错,但是结果不一定是200
try {
String string = responseBody.string();
if (callBack!=null){
callBack.successData(string);
Log.i("AA", "onNext: 请求"+string);
}
} catch (Exception e) {
e.printStackTrace();
if (callBack!=null){
callBack.failureData(e.getMessage());
Log.i("AA", "onNext: Exception请求"+e.getMessage());
}
}
}
};
return observer;
}
//回调
public interface ICallBack {
void successData(String result);
void failureData(String error);
}
}
举例子 点击事件里调用了get post 请求方法
@OnClick({R.id.mButton, R.id.mButtonPost})
public void onClick(View view) {
switch (view.getId()) {
case R.id.mButton://GET请求
RetrofitManager.getInstance().doGet(Base_Url, new RetrofitManager.ICallBack() {
@Override
public void successData(String result) {
Log.i("AA", "onResponse: " + result + "返回值");
}
@Override
public void failureData(String error) {
Log.i("AA", "error: " + error + "M错");
}
});
break;
case R.id.mButtonPost://POST请求
Map map = new HashMap<>();
map.put("phone","15000000000");
map.put("pwd","1111");
RetrofitManager.getInstance().doPost(BasePost_Url, map, new RetrofitManager.ICallBack() {
@Override
public void successData(String result) {
//需要解析的
Gson gson = new Gson();
PostBean bean = gson.fromJson(result, PostBean.class);
String name = bean.getResult().getNickName();
Log.i("AA", "result: " + name.toString() + "名字");
}
@Override
public void failureData(String error) {
Log.i("AA", "result: " + error.toString() + "M错");
}
});
break;
}
}