天天看点

安卓框架搭建(六)Retrofit网络请求(简单封装)

前言:

网络请求是绝大多数app中比不可少的工具,对于我而言,从最初的xutils,到vollay,再到okhttp,最后到了今天的retrofit,相对而言,每个都有每个的优点,并不能完全说谁好谁坏,其实我觉得用你最熟悉的,你觉得最好的,最方便的,他就是最好的,到目前为止,我相信还是有一些公司的项目在用xutils,或者vollay的,如果说盲目的追求新东西,而最后出现一堆bug,这恐怕是所有程序猿最不想看到的结果,只要你技术过硬,你就能封装一套最适合你的,好了废话不多说,下面我就带领大家来简单的封装一套属于你自己的retrofit网络请求,让你的网络请求更简单方便,此封装并没有包含所有请求方式,这里只以get请求为例,其他方式自行开阔,后续会将所有请求方式添加到 YcRetrofitUtils源码中,

1.添加相关依赖

//文件内部使用
def butterknifeLatestReleaseVersion = '8.5.1' //butterknife插件的版本
def supportLibraryVersion = '27.1.1'
//外部使用的安卓版本相关
ext {
    applicationId = 'com.yc.androidarchitecture'
    compileSdkVersion = 27
    targetSdkVersion = 27
    minSdkVersion = 19
    buildToolsVersion = "27.1.1"
    versionCode = 0
    versionName = "1.0.0"
}

//compile依赖的第三方库
ext.deps = [
        supportv4                  : "com.android.support:support-v4:$supportLibraryVersion",
        supportv7                  : "com.android.support:appcompat-v7:$supportLibraryVersion",
        recyclerviewv7             : "com.android.support:recyclerview-v7:$supportLibraryVersion",
        constraintlayout           : 'com.android.support.constraint:constraint-layout:1.1.2',
//增加butterknife 插件相关的库 (版本用内部定义的方式,方便管理)
        butterknife                : "com.jakewharton:butterknife:$butterknifeLatestReleaseVersion",
        butterknifeCompiler        : "com.jakewharton:butterknife-compiler:$butterknifeLatestReleaseVersion",
        YcAndroidUtils             : 'com.yc:YcAndroidUtils:1.1.7',
        design                     : "com.android.support:design:$supportLibraryVersion",

//网络请求依赖库
        rxjava                     : "io.reactivex.rxjava2:rxjava:2.1.1",
        rxandroid                  : "io.reactivex.rxjava2:rxandroid:2.0.1",
        retrofit                   : "com.squareup.retrofit2:retrofit:2.3.0",
        retrofit2_converter_gson   : "com.squareup.retrofit2:converter-gson:2.3.0",
        retrofit2_adapter_rxjava2  : "com.squareup.retrofit2:adapter-rxjava2:2.3.0",
        okhttp3_logging_interceptor: "com.squareup.okhttp3:logging-interceptor:3.10.0",
]
           

在Application中初始化一下工具类

/**
         * 设置baseUrl 及 ApiService (必填项)
         * 如果你觉得 BaseApiService默认的不能满足你的需求 可继承BaseApiService后传入你自己定义的BaseApiService
         */
        YcRetrofitUtils builder = YcRetrofitUtils.getInstance()
                .init(this) //初始化
                .setBaseUrl("http://v.juhe.cn/")
//                .setReadTimeOut(100)//默认 60000
//                .setWriteTimeOut(100)//默认 60000
//                .setConnectTimeout(100)//默认 60000
                .build()
                .create();
        basicUseService = builder.create(BasicUseService.class);
           

2.在base类中创建 BaseApiService,这里只实现get方式,其他的方式根据需求自己添加就好

/**
 * Created by yc on 2018/4/3.
 */
public interface BaseApiService {

   @GET()
    Flowable<ResponseBody> get(@Url String url);

    @GET()
    Flowable<ResponseBody> get(@Url String url, @QueryMap Map<String, String> maps);

    @POST()
    @FormUrlEncoded
    Flowable<ResponseBody> post(@Url String url, @FieldMap Map<String, String> maps);

    @POST()
    Flowable<ResponseBody> postBody(@Url String url, @Body Object object);

    @DELETE()
    Flowable<ResponseBody> delete(@Url String url, @QueryMap Map<String, String> maps);

    @PUT()
    Flowable<ResponseBody> put(@Url String url, @QueryMap Map<String, String> maps);

    @POST()
    Flowable<ResponseBody> putBody(@Url String url, @Body Object object);

    @Multipart
    @POST()
    Flowable<ResponseBody> uploadFlie(@Url String fileUrl, @Part("description") RequestBody description, @Part("files") MultipartBody.Part file);

    @Multipart
    @POST()
    Flowable<ResponseBody> uploadFiles(@Url String url, @PartMap() Map<String, RequestBody> maps);

    @Multipart
    @POST()
    Flowable<ResponseBody> uploadFiles(@Url String url, @Part() List<MultipartBody.Part> parts);

    @Streaming
    @GET
    Flowable<ResponseBody> downloadFile(@Url String fileUrl);

    @POST()
    @Headers({"Content-Type: application/json", "Accept: application/json"})
    Flowable<ResponseBody> postJson(@Url String url, @Body RequestBody jsonBody);

    @POST()
    Flowable<ResponseBody> postBody(@Url String url, @Body RequestBody body);
}
           

3.工具类的封装在代码中详细讲解

public class YcRetrofitUtils {

    private static Application sContext;
    public static final int DEFAULT_MILLISECONDS = 60000;             //默认的超时时间
    private static final int DEFAULT_RETRY_COUNT = 3;                 //默认重试次数
    private static final int DEFAULT_RETRY_INCREASEDELAY = 0;         //默认重试叠加时间
    private static final int DEFAULT_RETRY_DELAY = 500;               //默认重试延时
    public static final int DEFAULT_CACHE_NEVER_EXPIRE = -1;          //缓存过期时间,默认永久缓存
    private String mBaseUrl;                                          //全局BaseUrl
    private long mConnectTimeout;                                      //链接超时
    private long mReadTimeOut;                                         //读超时
    private long mWriteTimeOut;                                        //写超时
    private static int mRetryCount = DEFAULT_RETRY_COUNT;                    //重试次数默认3次
    private static int mRetryDelay = DEFAULT_RETRY_DELAY;                    //延迟xxms重试
    private static int mRetryIncreaseDelay = DEFAULT_RETRY_INCREASEDELAY;    //叠加延迟
    private OkHttpClient.Builder okHttpClientBuilder;                 //okhttp请求的客户端
    private Retrofit.Builder retrofitBuilder;                         //Retrofit请求Builder
    private Retrofit retrofit;
    private Interceptor mInterceptor;                                 //okhttp的拦截器
    private Converter.Factory mConverterFactory;                      //Retrofit全局设置Converter.Factory
    private CallAdapter.Factory mCallAdapterFactory;                  //Retrofit全局设置CallAdapter.Factory

    private static BaseApiService mBaseApiService;                         //通用的的api接口
    //定义公共的参数
    private static Map<String, RequestBody> params;
    private volatile static YcRetrofitUtils sInstance = null;
    private static DisposableSubscriber sDisposableSubscriber;

    private YcRetrofitUtils() {
        okHttpClientBuilder = new OkHttpClient.Builder();
        retrofitBuilder = new Retrofit.Builder();

    }

    public static YcRetrofitUtils getInstance() {
        if (sInstance == null) {
            synchronized (YcRetrofitUtils.class) {
                if (sInstance == null) {
                    sInstance = new YcRetrofitUtils();
                    params = new HashMap<String, RequestBody>();
                }
            }
        }
        return sInstance;
    }

    public static BaseApiService getBaseApiService() {
        return mBaseApiService;
    }

    /**
     * 必须在全局Application先调用,获取context上下文,否则缓存无法使用
     */
    public YcRetrofitUtils init(Application app) {
        sContext = app;
        return this;
    }

    /**
     * 获取全局上下文
     */
    public static Context getContext() {
        initialize();
        return sContext;
    }

    private static void initialize() {
        if (sContext == null)
            throw new ExceptionInInitializerError("请先在全局Application中调用 YcRetrofitinit() 初始化!");
    }

    //okhttp的实例
    public static OkHttpClient getOkHttpClient() {
        return getOkHttpClientBuilder().build();
    }

    public static Retrofit getRetrofit() {
        return getRetrofitBuilder().build();
    }

    /**
     * 对外暴露 OkHttpClient,方便自定义
     */
    public static OkHttpClient.Builder getOkHttpClientBuilder() {
        return getInstance().okHttpClientBuilder;
    }

    /**
     * 对外暴露 Retrofit,方便自定义
     */
    public static Retrofit.Builder getRetrofitBuilder() {
        return getInstance().retrofitBuilder;
    }

    /**
     * 全局为Retrofit设置自定义的OkHttpClient
     */
    public YcRetrofitUtils setOkclient(OkHttpClient client) {
        getRetrofitBuilder().client(checkNotNull(client, "OkClient == null"));
        return this;
    }

    /**
     * 全局设置Interceptor,默认HttpLoggingInterceptor.Level.BODY
     */
    public YcRetrofitUtils addOkHttpInterceptor(Interceptor interceptor) {
        mInterceptor = checkNotNull(interceptor, "OkHttpAddInterceptor == null");
        getOkHttpClientBuilder().addInterceptor(mInterceptor);
        return this;
    }

    /**
     * 全局设置Converter.Factory,默认GsonConverterFactory.create()
     */
    public YcRetrofitUtils addConverterFactory(Converter.Factory factory) {
        mConverterFactory = checkNotNull(factory, "RetrofitConverterFactory == null");
        getRetrofitBuilder().addConverterFactory(mConverterFactory);
        return this;
    }

    /**
     * 全局设置CallAdapter.Factory,默认RxJavaCallAdapterFactory.create()
     */
    public YcRetrofitUtils addCallAdapterFactory(CallAdapter.Factory factory) {
        mCallAdapterFactory = checkNotNull(factory, "RetrofitCallAdapterFactory == null");
        getRetrofitBuilder().addCallAdapterFactory(mCallAdapterFactory);
        return this;
    }

    /**
     * 全局读取超时时间
     */
    public YcRetrofitUtils setReadTimeOut(long readTimeOut) {
        if (readTimeOut < 0)
            throw new IllegalArgumentException("retryCount must > 0");
        mReadTimeOut = readTimeOut;
        getOkHttpClientBuilder().readTimeout(readTimeOut, TimeUnit.MILLISECONDS);
        return this;
    }

    /**
     * 全局写入超时时间
     */
    public YcRetrofitUtils setWriteTimeOut(long writeTimeout) {
        if (writeTimeout < 0)
            throw new IllegalArgumentException("retryCount must > 0");
        mWriteTimeOut = writeTimeout;
        getOkHttpClientBuilder().writeTimeout(writeTimeout, TimeUnit.MILLISECONDS);
        return this;
    }

    /**
     * 全局连接超时时间
     */
    public YcRetrofitUtils setConnectTimeout(long connectTimeout) {
        if (connectTimeout < 0)
            throw new IllegalArgumentException("retryCount must > 0");
        mConnectTimeout = connectTimeout;
        getOkHttpClientBuilder().connectTimeout(connectTimeout, TimeUnit.MILLISECONDS);
        return this;
    }

    /**
     * 超时重试次数
     */
    public YcRetrofitUtils setRetryCount(int retryCount) {
        if (retryCount < 0)
            throw new IllegalArgumentException("retryCount must > 0");
        mRetryCount = retryCount;
        return this;
    }

    /**
     * 超时重试次数
     */
    public static int getRetryCount() {
        return getInstance().mRetryCount;
    }

    /**
     * 超时重试延迟时间
     */
    public YcRetrofitUtils setRetryDelay(int retryDelay) {
        if (retryDelay < 0)
            throw new IllegalArgumentException("retryDelay must > 0");
        mRetryDelay = retryDelay;
        return this;
    }

    /**
     * 超时重试延迟时间
     */
    public static int getRetryDelay() {
        return getInstance().mRetryDelay;
    }

    /**
     * 超时重试延迟叠加时间
     */
    public YcRetrofitUtils setRetryIncreaseDelay(int retryIncreaseDelay) {
        if (retryIncreaseDelay < 0)
            throw new IllegalArgumentException("retryIncreaseDelay must > 0");
        mRetryIncreaseDelay = retryIncreaseDelay;
        return this;
    }

    /**
     * 超时重试延迟叠加时间
     */
    public static int getRetryIncreaseDelay() {
        return getInstance().mRetryIncreaseDelay;
    }

    /**
     * 全局设置baseurl
     */
    public YcRetrofitUtils setBaseUrl(String baseUrl) {
        mBaseUrl = checkNotNull(baseUrl, "baseUrl == null");
        return this;
    }

    /**
     * 获取全局baseurl
     */
    public static String getBaseUrl() {
        return getInstance().mBaseUrl;
    }

    /**
     * 根据当前的请求参数,生成对应的OkClient
     */
    private OkHttpClient.Builder generateOkClient() {
        if (mConnectTimeout <= 0)
            setConnectTimeout(DEFAULT_MILLISECONDS);
        if (mReadTimeOut <= 0)
            setReadTimeOut(DEFAULT_MILLISECONDS);
        if (mWriteTimeOut <= 0)
            setWriteTimeOut(DEFAULT_MILLISECONDS);

        if (mInterceptor == null) {
            //由于Retrofit是基于okhttp的所以,要先初始化okhttp相关配置
            HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
            // BASIC,BODY,HEADERS
            interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
            //添加拦截器
            addOkHttpInterceptor(interceptor);
        }
        return getOkHttpClientBuilder();
    }

    /**
     * 根据当前的请求参数,生成对应的Retrofit
     */
    private Retrofit.Builder generateRetrofit() {

        final Retrofit.Builder retrofitBuilder = getRetrofitBuilder().baseUrl(checkNotNull(getBaseUrl(), "baseUrl == null"));
        if (mConverterFactory == null)
            addConverterFactory(GsonConverterFactory.create());

        if (mCallAdapterFactory == null)
            addCallAdapterFactory(RxJava2CallAdapterFactory.create());

        return retrofitBuilder;
    }


    /**
     * 生成网络请求build请求体
     *
     * @return
     */
    public YcRetrofitUtils build() {

        OkHttpClient.Builder okHttpClientBuilder = generateOkClient();

        final Retrofit.Builder retrofitBuilder = generateRetrofit();
        retrofitBuilder.client(okHttpClientBuilder.build());
        if (retrofit == null) {
            retrofit = retrofitBuilder.build();
        }
        return this;
    }

    public YcRetrofitUtils create() {
        mBaseApiService = create(BaseApiService.class);
        return this;
    }

    /**
     * 创建api服务  可以支持自定义的api,默认使用BaseApiService,上层不用关心
     *
     * @param service 自定义的apiservice class
     */
    public <T> T create(final Class<T> service) {
        retrofit = checkNotNull(retrofit, "请先在调用build()才能使用");
        return retrofit.create(service);
    }

    public static <T> T checkNotNull(T t, String message) {
        if (t == null) {
            throw new NullPointerException(message);
        }
        return t;
    }
    /**
     * 添加参数
     * 根据传进来的Object对象来判断是String还是File类型的参数
     */
    public YcRetrofitUtils addParameter(String key, Object o) {
        if (params != null && params.size() > 0)
            clear();
        if (o instanceof String) {
            RequestBody body = RequestBody.create(MediaType.parse("text/plain;charset=UTF-8"), (String) o);
            params.put(key, body);
        } else if (o instanceof File) {
            RequestBody body = RequestBody.create(MediaType.parse("multipart/form-data;charset=UTF-8"), (File) o);
            params.put(key + "\"; filename=\"" + ((File) o).getName() + "", body);
        }
        return this;
    }
    /**
     * 构建RequestBody
     */
    public Map<String, RequestBody> bulider() {

        return params;
    }

    public void clear() {
        params.clear();
    }


    /**
     * get
     *
     * @param url              链接
     * @param callBackListener 回调监听
     */
    public static void get(String url, final OnCallBackListener callBackListener) {
        get(url, "", callBackListener);
    }

    /**
     * get
     *
     * @param url              链接
     * @param tag              类型
     * @param callBackListener 回调监听
     */
    public static void get(String url, String tag, final OnCallBackListener callBackListener) {
        Flowable flowable = mBaseApiService.get(url);
        requestCallBack(flowable, tag, callBackListener);
    }

    /**
     * get
     *
     * @param url              链接
     * @param map              参数
     * @param callBackListener 回调监听
     */
    public static void get(String url, Map map, final OnCallBackListener callBackListener) {
        get(url, map, "", callBackListener);
    }

    /**
     * get
     *
     * @param url              链接
     * @param map              参数
     * @param tag              类型
     * @param callBackListener 回调监听
     */
    public static void get(String url, Map map, String tag, final OnCallBackListener callBackListener) {
        Flowable flowable = mBaseApiService.get(url, map);
        requestCallBack(flowable, tag, callBackListener);
    }


    /**
     * post
     *
     * @param url              链接
     * @param map              参数
     * @param callBackListener 回调监听
     */
    public static void post(String url, Map map, final OnCallBackListener callBackListener) {
        Flowable flowable = mBaseApiService.post(url, map);
        requestCallBack(flowable, "", callBackListener);
    }

    /**
     * post
     *
     * @param url              链接
     * @param map              参数
     * @param callBackListener 回调监听
     * @param tag              调用的方法类型(区分调用的方法的回调参数)
     */
    public static void post(String url, Map map, String tag, final OnCallBackListener callBackListener) {
        Flowable flowable = mBaseApiService.post(url, map);
        requestCallBack(flowable, tag, callBackListener);
    }

    //===============================================================

    /**
     * 处理数据请求相关功能,将flowable加入队列,通过接口回调的方式将rxjava返回的数据返回给调用者
     *
     * @param flowable         调入的flowable
     * @param callBackListener 回调
     * @param <T>              泛型参数
     */

    public static <T> void requestCallBack(Flowable<T> flowable, final OnCallBackListener callBackListener) {
        requestCallBack(flowable, "", callBackListener);
    }

    /**
     * 处理数据请求相关功能,将flowable加入队列,通过接口回调的方式将rxjava返回的数据返回给调用者
     *
     * @param callBackListener 回调
     * @param tag              调用方法标志,回调用
     * @param <T>              泛型参数
     */

    public static <T> void requestCallBack(Flowable<T> flowable, final String tag, final OnCallBackListener callBackListener) {
        sDisposableSubscriber = requestCallBack(tag, callBackListener);
        onSubscribe(flowable, sDisposableSubscriber);
    }

    public static <T> DisposableSubscriber requestCallBack(final String tag, final OnCallBackListener callBackListener) {
        sDisposableSubscriber = new DisposableSubscriber<T>() {
            @Override
            public void onNext(T body) {
                try {
                    if (body instanceof ResponseBody) {
                        String response = ((ResponseBody) body).string();
                        callBackListener.onSuccess(response, tag);
                    } else {
                        callBackListener.onSuccess(body, tag);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    callBackListener.onFailed(e.getMessage().toString(), tag);
                }
            }

            @Override
            public void onError(Throwable t) {
                callBackListener.onFailed(t.getMessage().toString(), tag);
            }

            @Override
            public void onComplete() {

            }
        };

        return sDisposableSubscriber;
    }


    public static <T> void onSubscribe(Flowable<T> flowable) {
        onSubscribe(flowable, sDisposableSubscriber);
    }

    public static <T> void onSubscribe(Flowable<T> flowable, DisposableSubscriber<T> disposableSubscriber) {
        Flowable<T> beanFlowable = flowable.subscribeOn(Schedulers.io());
        beanFlowable.observeOn(AndroidSchedulers.mainThread())
                .retryWhen(new RetryExceptionFunc(mRetryCount, mRetryDelay, mRetryIncreaseDelay))
                .subscribeWith(disposableSubscriber);
    }

    /**
     * 取消订阅
     */
    public static void cancelSubscription() {
        cancelSubscription(sDisposableSubscriber);
    }

    /**
     * 取消订阅
     */
    public static void cancelSubscription(Disposable disposable) {
        if (disposable != null && !disposable.isDisposed()) {
            disposable.dispose();
        }
    }
           

超时相关工具:

/**
 * <p>描述:网络请求错误重试条件</p>
 */
public class RetryExceptionFunc implements Function<Flowable<? extends Throwable>, Flowable<?>> {
    /* retry次数*/
    private int count = 0;
    /*延迟*/
    private long delay = 500;
    /*叠加延迟*/
    private long increaseDelay = 3000;

    public RetryExceptionFunc() {

    }

    public RetryExceptionFunc(int count, long delay) {
        this.count = count;
        this.delay = delay;
    }

    public RetryExceptionFunc(int count, long delay, long increaseDelay) {
        this.count = count;
        this.delay = delay;
        this.increaseDelay = increaseDelay;
    }

    @Override
    public Flowable<?> apply(Flowable<? extends Throwable> flowable) throws Exception {
        return flowable.zipWith(Flowable.range(1, count + 1), new BiFunction<Throwable, Integer, Wrapper>() {
            @Override
            public Wrapper apply(Throwable throwable, Integer integer) throws Exception {
                return new Wrapper(throwable, integer);
            }
        }).flatMap(new Function<Wrapper, Publisher<?>>() {
            @Override
            public Publisher<?> apply(Wrapper wrapper) throws Exception {
                if ((wrapper.throwable instanceof ConnectException
                        || wrapper.throwable instanceof SocketTimeoutException
                        || wrapper.throwable instanceof ConnectTimeoutException
                        || wrapper.throwable instanceof SocketTimeoutException
                        || wrapper.throwable instanceof TimeoutException)
                        && wrapper.index < count + 1) { //如果超出重试次数也抛出错误,否则默认是会进入onCompleted
                    return Flowable.timer(delay + (wrapper.index - 1) * increaseDelay, TimeUnit.MILLISECONDS);

                }
                return Flowable.error(wrapper.throwable);
            }
        });
    }

    private class Wrapper {
        private int index;
        private Throwable throwable;

        public Wrapper(Throwable throwable, int index) {
            this.index = index;
            this.throwable = throwable;
        }
    }

}
           

4.定义回调监听接口

public interface OnRequestCallBackListener<T> {
    void onSuccess(T result, String type);

    void onFailed(String e, String type);

}
           

5.使用方法:

get方法:

Map map = new HashMap();
        map.put("key", "你自己的key");
        map.put("type", "top");
        RetrofitUtils.getInstance().get(UrlConfig.NEWS_URL, map, new OnRequestCallBackListener<ResponseBody>() {
            @Override
            public void onSuccess(ResponseBody result, String type) {
                try {
                    NewsBean newsBean = new Gson().fromJson(result.string(), NewsBean.class);
                    List<NewsBean.ResultBean.DataBean> data = newsBean.getResult().getData();
                    //通过回调将数据返回给 model层
                    callBackListener.onSuccess(data);
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onFailed(String e, String type) {
                callBackListener.onFailed(e);
            }
        });
           

post方法:

RetrofitUtils instance = RetrofitUtils.getInstance();
        instance.addParameter("key", "你自己的key");
        instance.addParameter("type", "top");
        Map<String, RequestBody> bulider = instance.bulider();
        instance.post(UrlConfig.NEWS_URL, bulider, new OnRequestCallBackListener<ResponseBody>() {
            @Override
            public void onSuccess(ResponseBody result, String type) {
               NewsBean newsBean = new Gson().fromJson(result.string(), NewsBean.class);
                    List<NewsBean.ResultBean.DataBean> data = newsBean.getResult().getData();
                    //通过回调将数据返回给 model层
                    callBackListener.onSuccess(data);
            }

            @Override
            public void onFailed(String e, String type) {
                callBackListener.onFailed(e);
            }
        });
           

上传图文:

RetrofitUtils instance = RetrofitUtils.getInstance();
      
        File file = new File(mImagePath);
        instance.addParameter("avatar", file);

        instance.addParameter("key", "你自己的key");
        instance.addParameter("type", "top");
        Map<String, RequestBody> bulider = instance.bulider();
        instance.post(UrlConfig.NEWS_URL, bulider, new OnRequestCallBackListener<ResponseBody>() {
            @Override
            public void onSuccess(ResponseBody result, String type) {
             
             try {
                    NewsBean newsBean = new Gson().fromJson(result.string(), NewsBean.class);
                    List<NewsBean.ResultBean.DataBean> data = newsBean.getResult().getData();
                    //通过回调将数据返回给 model层
                    callBackListener.onSuccess(data);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailed(String e, String type) {
                callBackListener.onFailed(e);
            }
        });
           

你也可以自定义自己的api

public interface BasicUseService {

    //方式一
    @GET("{path}")
    Flowable<NewsBean> login(@Path("path") String path, @QueryMap Map<String, String> maps);

    //方式二
    @GET()
    Flowable<NewsBean> login1(@Url String url, @QueryMap Map<String, String> maps);

    //方式三
    @GET("toutiao/index")
    Flowable<NewsBean> login2(@QueryMap Map<String, String> maps);

}
           

用法:

mMap = new HashMap();
                mMap.put("key", "4a216a3fde4361f175aa2678dada199b");
                mMap.put("type", "top");
//                BasicUseService basicUseService = YcRetrofitUtils.getRetrofit().create(BasicUseService.class);
                Flowable login = basicUseService.login("toutiao/index", mMap);
                YcRetrofitUtils.requestCallBack(login, "", new OnCallBackListener() {
                    @Override
                    public <Q> void onSuccess(Q body, String tag) {
                        if (body instanceof NewsBean) {
                            Toast.makeText(MainActivity.this, body.toString(), Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onFailed(String e, String tag) {

                    }
                });
           

在addParameter方法中会根据传入的velue 来判断是传入的是string 字符串还是 file 文件

此方式有一个弊端就是 没有用到retrofit 转换bean的方式

使用方式看起来就是这么简单,这里注意的是url采用的是传参的方式,并没有用base中注解的方式,可根据需要进行修改

以上就是,安卓框架搭建(六)Retrofit网络请求(简单封装),的全部内容

如有不了解的 可以去github下载源码 本章节内容为分支6 (由于后期优化,分支6不是最新代码,最新的可到主分支查看网络封装,或到 YcRetrofitUtils源码中 查看具体内容)

github源码地址,本章节见dev6分支

或 加入安卓开发交流群:安卓帮595856941

相关链接:

下一篇:

安卓框架搭建(七)BaseAdapter的封装