Retrofit 2.0 + OkHttp 3.0 配置

时间 : 16-06-30 栏目 : Android, 移动开发 作者 : noway 评论 : 0 点击 : 345 次

来自: http://drakeet.me/retrofit-2-0-okhttp-3-0-config

Retrofit 和 OkHttp 都是伟大的 Square 公司开源的伟大项目。我从 2014 年便在同事 ionull 的推荐带领下,使用这个网络库组合以及 RxJava,真是极大改善 Android 开发体验的好东西。前段时间也是从 Retrofit 1.9 升级到 2.0 beta 4 版本,从 OkHttp 2.+ 版本升级到  3.0.1 版本。这两者在各自的这两个大版本升级中,都改变了不少,使得原本的代码都需要进行一些修改才能使用,我也是稍微摸索了几下,如今大致摸清,把一些基础配置,比如设置 Json 转换器、Rx Java 适配器、设置 Debug Log 模式、设置超时、错误重连,以及配置 Access token Interceptor 等等一些内容,分享一下。

引入依赖:

compile 'com.squareup.retrofit2:retrofit:2.0.0-beta4'
compile 'com.squareup.retrofit2:converter-gson:2.0.0-beta4'
compile 'com.squareup.retrofit2:adapter-rxjava:2.0.0-beta4'
compile 'com.squareup.okhttp3:okhttp:3.0.1'
compile 'com.squareup.okhttp3:logging-interceptor:3.0.1'

先说 OkHttp 3.0 的配置,3.0 使用层面上的主要改变是,由原本的 okHttp 对象直接各种 set 进行配置改为 Builder 配置模式,所以原本对应的方法应该到 OkHttpClient.Builder 类对象下寻找。我的一些常用配置如下:

HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient client = new OkHttpClient.Builder()
        .addInterceptor(interceptor)
        .retryOnConnectionFailure(true)
        .connectTimeout(15, TimeUnit.SECONDS)
        .addNetworkInterceptor(mTokenInterceptor)
        .build();

解释:

  • HttpLoggingInterceptor 是一个拦截器,用于输出网络请求和结果的 Log,可以配置 level 为 BASIC / HEADERS / BODY,都很好理解,对应的是原来 retrofit 的 set log level 方法,现在 retrofit 已经没有这个方法了,所以只能到 OkHttp 这边来配置,并且 BODY 对应原来到 FULL.
  • retryOnConnectionFailure 方法为设置出现错误进行重新连接。
  • connectTimeout 设置超时时间
  • addNetworkInterceptor 让所有网络请求都附上你的拦截器,我这里设置了一个 token 拦截器,就是在所有网络请求的 header 加上 token 参数,下面会稍微讲一下这个内容。

让所有网络请求都附上你的拦截器:

Interceptor mTokenInterceptor = new Interceptor() {
    @Override public Response intercept(Chain chain) throws IOException {
        Request originalRequest = chain.request();
        if (Your.sToken == null || alreadyHasAuthorizationHeader(originalRequest)) {
            return chain.proceed(originalRequest);
        }
        Request authorised = originalRequest.newBuilder()
            .header("Authorization", Your.sToken)
            .build();
        return chain.proceed(authorised);
    }
};

解释:

  • 那个 if 判断意思是,如果你的 token 是空的,就是还没有请求到 token,比如对于登陆请求,是没有 token 的,只有等到登陆之后才有 token,这时候就不进行附着上 token。另外,如果你的请求中已经带有验证 header 了,比如你手动设置了一个另外的 token,那么也不需要再附着这一个 token.
  • header 的 key 通常是 Authorization,如果你的不是这个,可以修改。

如果你需要在遇到诸如 401 Not Authorised 的时候进行刷新 token,可以使用 Authenticator,这是一个专门设计用于当验证出现错误的时候,进行询问获取处理的拦截器:

Authenticator mAuthenticator = new Authenticator() {
    @Override public Request authenticate(Route route, Response response)
            throws IOException {
        Your.sToken = service.refreshToken();
        return response.request().newBuilder()
                       .addHeader("Authorization", newAccessToken)
                       .build();        
    }
}

然后,对于以上的两个拦截器,分别使用 OkHttpClient.Builder 对象的 addNetworkInterceptor(mTokenInterceptor) 和 authenticator(mAuthenticator) 即可。

Retrofit:

对于 Retrofit,我的配置是:

Retrofit retrofit = new Retrofit.Builder()
        .baseUrl(AppConfig.BASE_URL)
        .client(client)
        .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
        .addConverterFactory(GsonConverterFactory.create(gson))
        .build();
service = retrofit.create(YourApi.class);

解释:

  • baseUrl: 原来的 setEndPoint 方法变成了 baseUrl
  • client 即上面的 OkHttp3 对象
  • addCallAdapterFactory 增加 RxJava 适配器
  • addConverterFactory 增加 Gson 转换器

本文标签

除非注明,文章均为( noway )原创,转载请保留链接: http://blog-old.z3a105.com/?p=844

Retrofit 2.0 + OkHttp 3.0 配置:等您坐沙发呢!

发表评论





       ==QQ:122320466==

 微信    QQ群


0

Aujourd’hui, une partie avec le développement du e-commerce, achats en ligne est devenu une partie de la vie pour beaucoup de gens. La mariage a commencé achats en ligne. Si vous choisissez achats les mariages en ligne, il peut être beaucoup moins cher que le salon de la Robe de mariée pas chermariée local, réduisant le budget de mariage. vous pouvez avoir beaucoup de choix si acheter de mariage en ligne. vous pouvez ramasser une robe de mariée bon marché sur Internet.
Piercing fascinerande figur, och nu tittar vi på 2016 senast brudklänning, kan du vara den vackraste bruden det!2016 senaste Bra brudklänning, söt temperament Bra design, romantiska spetsar blomma kjol, som du lägger till en elegant och charmig temperament.Kvinnan tillbaka mjuka linjer, människor brudklänningofta få en känsla av oändlig frestelse. Fall 2016 mässan, lämnar uppgifter om ditt bröllop charmig.
Yesterday afternoon, the Chinese team was training in the Guangzhou Gymnasium, when the reporter asked Zhao Yunlei the feeling of wearing the new cheap jersey , cheap jerseys online shopshe readily took a shirt from the bag crumpled ball to reporters, and she said with a smile: ” This shirt is light. ”Zhao Yunlei said: “Our material is very light like with the clothes of the tennis King Nadal, Federer, after the sweat, sweat does not drip down to the ground, when we do move, it is easy pace slipping if the sweat drip on the floor.”Tennis players Zhang Yawen, told reporters: “You might think the clothes attached to the body, fearing we swing will be affected, in fact, we do not feel anything, because the clothes are very light, very soft, put on quite comfortable. And it’s particularly good clothes to dry, washing and will dry in 15 minutes. ”
China’s sports enthusiasts NFL sweatshirt with mad love and the pursuit of, and therefore, NFL jerseys have a good market in China and development. China is a populous country, is the consumer, the economic momentum is so good, the sales prospects sportswear is immeasurable. With hot sales sweatshirt, but also to promote the importance of sports fans, on health, on the other hand is a matter of concern for the World Cup, fans wearing NFL jerseys and also can express themselves more fully love and obsession Therefore, NFL jerseys Wholesale jerseys online shopwholesale has good prospects and development in China.
ANTA-ANTA Sports Products Limited, referred to as ANTA Sports, Anta, is China’s leading sporting goods companies, mainly engaged in the design, development, manufacture and marketing of ANTA brand sporting goods, including sports footwear, apparel and accessories. Anta sweatshirt design advantages, warm stretch knit fabric, using Slim version of model, more personal fit, bid farewell to bloated, so wearing more stylish.GUIRENNIAO-This logo is a spiritual totem, smooth graphics implication unstoppable force; flexible deliver an elegant arc Wholesale jerseys china shop movement, strength and speed of the United States, a symbol of passion and rationality publicity “Heart” and “meaning”, “concept” unity; pass the fearless and enterprising mind, showing beyond the realm of self, to unstoppable force to create the future.XTEP-Xtep (China) Co., Ltd. is a comprehensive development wholesale jerseys china shop, production and marketing of Xtep brand (XTEP) sports shoes, clothing, bags, caps, balls, socks mainly large sporting goods industry enterprises.
There are a lot of fans in identifying the authenticity of the above cheap jerseys have great distress, so here to i will show you some methods to definitely affordable inexpensive cheap jerseys : Firstly, we should look at if it is working fine. China has been called the world’s factory, a lot cheap jerseys factories in China have foundries, but our cheap jerseys are all from here! Secondly, should to see whether it is the , we all know that it is difficult to get out of print once a genuine cheap cheap jerseys free shipping jersey was print. and we have all kind of stocka on the whole website, in other words, we have all you want ! Finally, look at the price, our price is not necessarily the lowest in the whole website but it must be most fair on the whole website, we certainly you will not regret later when you buy it. Of course, except that cheap jerseys, we also have the other products, such as socks, leggings and some other related products, everyone can enjoy the best services of here!

KUBET