Retrofit 简单封装

首先在app/build.gradle/dependencies{}中添加所需的外部依赖

    compile 'com.squareup.retrofit2:retrofit:2.3.0'
    compile 'com.squareup.retrofit2:converter-gson:2.1.0'
    compile 'com.squareup.retrofit2:adapter-rxjava:2.1.0'
    //ConverterFactory的String依赖包
    compile 'com.squareup.retrofit2:converter-scalars:2.0.0'
    compile 'io.reactivex:rxandroid:1.1.0'

project/build.gradle/allprojects/repositories{}中配置该项目的存储库

//从https://jitpack.io下载支持的repositories
maven { url "https://jitpack.io" }

》》下面就是正式的封装开始了

  • 首先创建一个AnBaseApiServiceManger.class
    此类主要完成一些okhttp的配置,比如:缓存、cookie等...
    • 我们在AnBaseApiServiceManger.class中实现此类的空构造方法public AnBaseApiServiceManger(){},其次初始化 OkHttpClient.Builder()得到 builder 对象,通过 builder 对象对 okhttp 配置(下面看代码)
//初始化---获得builder对象
OkHttpClient.Builder builder = new OkHttpClient.Builder();
 //头
builder .addInterceptor(headerInterceptor)
 //缓存拦截
builder .addNetworkInterceptor(cacheInterceptor)
//缓存
builder .cache(cache)
//设置超时--链接--读取--写入
builder  .connectTimeout(15, TimeUnit.SECONDS)
builder  .readTimeout(20, TimeUnit.SECONDS)
builder  .writeTimeout(20, TimeUnit.SECONDS)
//设置cookie
builder  .cookieJar(cookieManager)
//错误重连
builder .retryOnConnectionFailure(true)
builder  .build();
  • 设置builder .addInterceptor(headerInterceptor)需要的头headerInterceptor
    Interceptor headerInterceptor = new Interceptor() {

          @Override
          public Response intercept(Chain chain) throws IOException {
              Request orignaRequest = chain.request();
              Request request = orignaRequest.newBuilder()
                      .header("AppType", "TPOS")
                      .header("Content-Type", "application/json")
                      .header("Accept", "application/json")
                      .method(orignaRequest.method(), orignaRequest.body())
                      .build();

              return chain.proceed(request);
          }
      };
  • 设置缓存cache
      //缓存文件夹
      File cacheFile = new File(MyApplicarions.Companion.getmContext().getExternalCacheDir().toString(),"cache");
      //缓存大小为10M
      int cacheSize = 10 * 1024 * 1024;
      //创建缓存对象
      final Cache cache = new Cache(cacheFile,cacheSize);
  • 缓存拦截器 cacheInterceptor的配置
    创建类CacheInterceptor.class实现Interceptor接口中的intercept方法

public class CacheInterceptor implements Interceptor {

    @Override
    public Response intercept(Chain chain) throws IOException {


        //通过 CacheControl 控制缓存数据
        CacheControl.Builder cacheBuilder = new CacheControl.Builder();
        cacheBuilder.maxAge(0, TimeUnit.SECONDS);//这个是控制缓存的最大生命时间
        cacheBuilder.maxStale(365, TimeUnit.DAYS);//这个是控制缓存的过时时间
        CacheControl cacheControl = cacheBuilder.build();

        //设置拦截器
        Request request = chain.request();
        if (!NetUtils.isNetworkAvailable(MyApplicarions.Companion.getmContext())) {
            request = request.newBuilder()
                    .cacheControl(cacheControl)
                    .build();
        }

/****************************************/
        //这个chain里面包含了request和response,所以你要什么都可以从这里拿
        long t1 = System.nanoTime();//请求发起的时间
        Log.e("LoggingInterceptor", String.format("发送请求 %s on %s%n%s", request.url(), chain.connection(), request.headers()));
/****************************************/

        Response originalResponse = chain.proceed(request);

/****************************************/
        long t2 = System.nanoTime();//收到响应的时间
        //这里不能直接使用response.body().string()的方式输出日志
        //因为response.body().string()之后,response中的流会被关闭,程序会报错,我们需要创建出一
        //个新的response给应用层处理
        ResponseBody responseBody = originalResponse.peekBody(1024 * 1024);
        Log.e("LoggingInterceptor", String.format("接收响应: [%s] %n返回json:【%s】 %.1fms%n%s",
                originalResponse.request().url(),
                responseBody.string(),
                (t2 - t1) / 1e6d,
                originalResponse.headers()));
/****************************************/

        if (NetUtils.isNetworkAvailable(MyApplicarions.Companion.getmContext())) {
            int maxAge = 0;//read from cache
            return originalResponse.newBuilder()
                    .removeHeader("Pragma")
                    .header("Cache-Control", "public ,max-age=" + maxAge)
                    .build();
        } else {
            int maxStale = 60 * 60 * 24 * 28;//tolerate 4-weeks stale
            return originalResponse.newBuilder()
                    .removeHeader("Prama")
                    .header("Cache-Control", "poublic, only-if-cached, max-stale=" + maxStale)
                    .build();
        }
    }
}
  • cookie的配置
    • 创建 OkHttpCookies.class实现序列化
public class OkHttpCookies implements Serializable {

    private transient final Cookie cookies;
    private transient Cookie clientCookies;

    public OkHttpCookies(Cookie cookies) {
        this.cookies = cookies;
    }

    public Cookie getCookies() {
        Cookie bestCookies = cookies;
        if (clientCookies != null) {
            bestCookies = clientCookies;
        }
        return bestCookies;
    }

    private void writeObject(ObjectOutputStream out) throws IOException {
        out.writeObject(cookies.name());
        out.writeObject(cookies.value());
        out.writeLong(cookies.expiresAt());
        out.writeObject(cookies.domain());
        out.writeObject(cookies.path());
        out.writeBoolean(cookies.secure());
        out.writeBoolean(cookies.httpOnly());
        out.writeBoolean(cookies.hostOnly());
        out.writeBoolean(cookies.persistent());
    }

    private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
        String name = (String) in.readObject();
        String value = (String) in.readObject();
        long expiresAt = in.readLong();
        String domain = (String) in.readObject();
        String path = (String) in.readObject();
        boolean secure = in.readBoolean();
        boolean httpOnly = in.readBoolean();
        boolean hostOnly = in.readBoolean();
        boolean persistent = in.readBoolean();
        Cookie.Builder builder = new Cookie.Builder();
        builder = builder.name(name);
        builder = builder.value(value);
        builder = builder.expiresAt(expiresAt);
        builder = hostOnly ? builder.hostOnlyDomain(domain) : builder.domain(domain);
        builder = builder.path(path);
        builder = secure ? builder.secure() : builder;
        builder = httpOnly ? builder.httpOnly() : builder;
        clientCookies = builder.build();
    }
}
  • 创建PersistentCookieStore.class将cookie本地化
public class PersistentCookieStore {
    private static final String LOG_TAG = "PersistentCookieStore";
    private static final String COOKIE_PREFS = "Cookies_Prefs";

    private final Map<String, ConcurrentHashMap<String, Cookie>> cookies;
    private final SharedPreferences cookiePrefs;


    public PersistentCookieStore(Context context) {
        cookiePrefs = context.getSharedPreferences(COOKIE_PREFS, 0);
        cookies = new HashMap<>();

        //将持久化的cookies缓存到内存中 即map cookies
        Map<String, ?> prefsMap = cookiePrefs.getAll();
        for (Map.Entry<String, ?> entry : prefsMap.entrySet()) {
            String[] cookieNames = TextUtils.split((String) entry.getValue(), ",");
            for (String name : cookieNames) {
                String encodedCookie = cookiePrefs.getString(name, null);
                if (encodedCookie != null) {
                    Cookie decodedCookie = decodeCookie(encodedCookie);
                    if (decodedCookie != null) {
                        if (!cookies.containsKey(entry.getKey())) {
                            cookies.put(entry.getKey(), new ConcurrentHashMap<String, Cookie>());
                        }
                        cookies.get(entry.getKey()).put(name, decodedCookie);
                    }
                }
            }
        }
    }

    protected String getCookieToken(Cookie cookie) {
        return cookie.name() + "@" + cookie.domain();
    }

    public void add(HttpUrl url, Cookie cookie) {
        String name = getCookieToken(cookie);

        //将cookies缓存到内存中 如果缓存过期 就重置此cookie
        if (!cookie.persistent()) {
            if (!cookies.containsKey(url.host())) {
                cookies.put(url.host(), new ConcurrentHashMap<String, Cookie>());
            }
            cookies.get(url.host()).put(name, cookie);
        } else {
            if (cookies.containsKey(url.host())) {
                cookies.get(url.host()).remove(name);
            }
        }

        //讲cookies持久化到本地
        SharedPreferences.Editor prefsWriter = cookiePrefs.edit();
        prefsWriter.putString(url.host(), TextUtils.join(",", cookies.get(url.host()).keySet()));
        prefsWriter.putString(name, encodeCookie(new OkHttpCookies(cookie)));
        prefsWriter.apply();
    }

    public List<Cookie> get(HttpUrl url) {
        ArrayList<Cookie> ret = new ArrayList<>();
        if (cookies.containsKey(url.host()))
            ret.addAll(cookies.get(url.host()).values());
        return ret;
    }

    public boolean removeAll() {
        SharedPreferences.Editor prefsWriter = cookiePrefs.edit();
        prefsWriter.clear();
        prefsWriter.apply();
        cookies.clear();
        return true;
    }

    public boolean remove(HttpUrl url, Cookie cookie) {
        String name = getCookieToken(cookie);

        if (cookies.containsKey(url.host()) && cookies.get(url.host()).containsKey(name)) {
            cookies.get(url.host()).remove(name);

            SharedPreferences.Editor prefsWriter = cookiePrefs.edit();
            if (cookiePrefs.contains(name)) {
                prefsWriter.remove(name);
            }
            prefsWriter.putString(url.host(), TextUtils.join(",", cookies.get(url.host()).keySet()));
            prefsWriter.apply();

            return true;
        } else {
            return false;
        }
    }

    public List<Cookie> getCookies() {
        ArrayList<Cookie> ret = new ArrayList<>();
        for (String key : cookies.keySet())
            ret.addAll(cookies.get(key).values());

        return ret;
    }

    /**
     * cookies 序列化成 string
     *
     * @param cookie 要序列化的cookie
     * @return 序列化之后的string
     */
    protected String encodeCookie(OkHttpCookies cookie) {
        if (cookie == null)
            return null;
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        try {
            ObjectOutputStream outputStream = new ObjectOutputStream(os);
            outputStream.writeObject(cookie);
        } catch (IOException e) {
            Log.d(LOG_TAG, "IOException in encodeCookie", e);
            return null;
        }

        return byteArrayToHexString(os.toByteArray());
    }

    /**
     * 将字符串反序列化成cookies
     *
     * @param cookieString cookies string
     * @return cookie object
     */
    protected Cookie decodeCookie(String cookieString) {
        byte[] bytes = hexStringToByteArray(cookieString);
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
        Cookie cookie = null;
        try {
            ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream);
            cookie = ((OkHttpCookies) objectInputStream.readObject()).getCookies();
        } catch (IOException e) {
            Log.d(LOG_TAG, "IOException in decodeCookie", e);
        } catch (ClassNotFoundException e) {
            Log.d(LOG_TAG, "ClassNotFoundException in decodeCookie", e);
        }

        return cookie;
    }

    /**
     * 二进制数组转十六进制字符串
     *
     * @param bytes byte array to be converted
     * @return string containing hex values
     */
    protected String byteArrayToHexString(byte[] bytes) {
        StringBuilder sb = new StringBuilder(bytes.length * 2);
        for (byte element : bytes) {
            int v = element & 0xff;
            if (v < 16) {
                sb.append('0');
            }
            sb.append(Integer.toHexString(v));
        }
        return sb.toString().toUpperCase(Locale.US);
    }

    /**
     * 十六进制字符串转二进制数组
     *
     * @param hexString string of hex-encoded values
     * @return decoded byte array
     */
    protected byte[] hexStringToByteArray(String hexString) {
        int len = hexString.length();
        byte[] data = new byte[len / 2];
        for (int i = 0; i < len; i += 2) {
            data[i / 2] = (byte) ((Character.digit(hexString.charAt(i), 16) << 4) + Character.digit(hexString.charAt(i + 1), 16));
        }
        return data;
    }
}
  • 创建CookieManger.class
    实现CookieJar实现方法saveFromResponse(HttpUrl url, List<Cookie> cookies)loadForRequest(HttpUrl url)对cookie进行管理
public class CookieManger implements CookieJar {


    private static Context mContext;

    private static PersistentCookieStore cookieStore;

    public CookieManger(Context context) {
        mContext = context;
        if (cookieStore == null) {
            cookieStore = new PersistentCookieStore(mContext);
        }

    }


    @Override
    public void saveFromResponse(HttpUrl url, List<Cookie> cookies) {
        if (cookies != null && cookies.size() > 0) {
            for (Cookie item : cookies) {
                cookieStore.add(url, item);
            }
        }
    }

    @Override
    public List<Cookie> loadForRequest(HttpUrl url) {
        List<Cookie> cookies = cookieStore.get(url);
        return cookies;
    }

}

创建URL基类AnCommonUrl.class
(此处为聚合接口数据,调用次数有限,如不能调用可能是次数已经用完)http://v.juhe.cn/movie/movies.today?key=103dcf8d180305642cda8efd7e8b85c0&cityid=2

public class AnCommonUrl {
    public static final String Base_Url = "http://v.juhe.cn/movie/";
}

创建客户端请求数据的接口AnApiService.class
根据自己的需求创建所要请求的方法(如:)

public interface AnApiService {

    /**
     * 今日放映影片
     *
     * @param cityid
     * @return
     */
    @GET("movies.today?key=103dcf8d180305642cda8efd7e8b85c0")
    Observable<TodayShowVideoBean> getTodayHost(@Query("cityid") int cityid);
}

Retrofit创建以及网络请求

  • 创建AnApiServiceManger.class
    • 首先做一个单利对外返回AnApiServiceManger.class的实例
private static AnApiServiceManger anApiServiceManger;

private AnApiServiceManger() {}

public static AnApiServiceManger getInstance() {
        if (anApiServiceManger == null) {
            synchronized (AnApiServiceManger.class) {
                if (anApiServiceManger == null) {
                    anApiServiceManger = new AnApiServiceManger();
                }
            }
        }
        return anApiServiceManger;
    }
  • AnApiServiceManger创建成功的构造方法中创建 Retrofit实例
    在创建之前让AnApiServiceManger.class继承AnBaseApiServiceManger.class(因为继承此后可以用过getOkHttpClient()获取OkHttpClient实例,再将实例的一些配置通过.client(getOkHttpClient())设置给Retrofit)
        //在构造方法中完成对Retrofit接口的初始化
        AnApiService anApiService= new Retrofit.Builder()
                // 设置baseUrl
                .baseUrl(AnCommonUrl.Base_Url)
                //设置OKHttpClient,如果不设置会提供一个默认的
                .client(getOkHttpClient())
                //添加Gson转换器
                .addConverterFactory(GsonConverterFactory.create(new GsonBuilder().setLenient().create()))
                // 使用RxJava作为回调适配器
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .build()
                .create(AnApiService.class);
  • 最后通过AnApiService实现客户端所需求的一些获取数据的方法
    /**
     * 今日放映影片
     * @param number 页码
     * @return
     */
 public Observable<TodayShowVideoBean> getTodayHost(int number){
        return anApiService.getTodayHost(number);
    }

最后在必要的地方调用数据

AnApiServiceManger.getInstance().getTodayHost(2).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<TodayShowVideoBean>() {
                    @Override
                    public void onCompleted() {
                       
                    }

                    @Override
                    public void onError(Throwable e) {
                       
                    }

                    @Override
                    public void onNext(TodayShowVideoBean todayShowVideoBean) {
                        
                    }
                });

请求结果:


发送请求结果.png
接收结果响应.png

后续 - 错误统一处理

Others...

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 213,186评论 6 492
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 90,858评论 3 387
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 158,620评论 0 348
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 56,888评论 1 285
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 66,009评论 6 385
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 50,149评论 1 291
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,204评论 3 412
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 37,956评论 0 268
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,385评论 1 303
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,698评论 2 327
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,863评论 1 341
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,544评论 4 335
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,185评论 3 317
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,899评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,141评论 1 267
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 46,684评论 2 362
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 43,750评论 2 351

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,644评论 18 139
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 171,900评论 25 707
  • 简介 刚接触Retrofit的时候,就写了一篇简单的使用介绍:Retrofit 2.0基本使用方法,算是对Retr...
    Whyn阅读 2,839评论 4 24
  • 1. Java基础部分 基础部分的顺序:基本语法,类相关的语法,内部类的语法,继承相关的语法,异常的语法,线程的语...
    子非鱼_t_阅读 31,605评论 18 399
  • 三月春盛,桃花灼灼 迎着四月微醺的春风 此时此刻做适宜做的事情就是 火锅鸡!!!吃吃吃!!! 最近“吃货”君的朋友...
    A湘满阁火锅鸡阅读 355评论 0 0