Retrofit2的 使用

需要导入的依赖
项目中

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'

MyApiService接口:

public interface MyApiService {

//第一个url是请求的接口域名,第二个是请求的参数,《ResponeseBody》是响应体,可以是T,可以是基本类
    @GET
    rx.Observable<ResponseBody> get(@Url String url, @QueryMap Map<String,String>map);

    @POST
    rx.Observable<ResponseBody>post(@Url String url,@QueryMap Map<String,String>map);
}

工具类:


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 = new Retrofit.Builder()
        	//添加Gson
                .addConverterFactory(GsonConverterFactory.create())
                //添加RxJava
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                //添加地址域名
                .baseUrl(Contacts.BASE_URL)
                //添加OkHttp
                .client(okHttpClient)
                .build();

//创建完retrofit,就可以调用myApiService里的方法了
        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<String,String>map)
    {
    //请求网络放在子线程
        myApiService.get(url,map).subscribeOn(Schedulers.io())
        //成功后回调到主线程(observeOn)是观察者
                .observeOn(AndroidSchedulers.mainThread())
                //订阅
                .subscribe(observer);
                //返回本类对象
        return RetrofitUtils.getInstance();
    }

    public RetrofitUtils post(String url,Map<String,String>map)
    {
        if(map==null)
        {
            map=new HashMap<>();
        }
        myApiService.post(url,map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(observer);
        return RetrofitUtils.getInstance();
    }

    private Subscriber<ResponseBody>subscriber=new Subscriber<ResponseBody>() {
        @Override
        public void onCompleted() {

        }

        @Override
        public void onError(Throwable e) {

        }

        @Override
        public void onNext(ResponseBody responseBody) {

        }
    };


    public Observer observer=new Observer<ResponseBody>() {
    //关闭
        @Override
        public void onCompleted() {

        }

//失败
        @Override
        public void onError(Throwable e) {
            if(httpListtener!=null)
            {
                httpListtener.OnError(e.getMessage());
            }
        }

//成功
        @Override
        public void onNext(ResponseBody responseBody) {
            if(httpListtener!=null)
            {
                try {
                    httpListtener.OnSuccess(responseBody.string());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    };


//自定义接口
    public interface HttpListtener
    {
        void OnSuccess(String jsonStr);

        void OnError(String error);
    }

    private HttpListtener httpListtener;

    public void setHttpListtener(HttpListtener listtener)
    {
        this.httpListtener=listtener;
    }

}

存放接口的类:

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";
}

动态获取权限

/**
         * 动态获取权限
         *
         * @param type
         */
        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 onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
            super.onRequestPermissionsResult(requestCode, permissions, grantResults);
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                startRequest(requestCode);
            }
        }

猜你喜欢

转载自blog.csdn.net/weixin_43564787/article/details/85555194