推荐阅读,猛戳:

1、Android MVP 实例

2、Android Retrofit 2.0使用

3、RxJava

4、RxBus

5、Android MVP+Retrofit+RxJava实践小结

之前分享的Android Retrofit 2.0 使用,属于基本的使用,实际开发还远远不够,因此对其补充,主要在Retrofit配置和接口参数。

Retrofit配置

添加依赖

app/build.gradle

 compile 'com.squareup.retrofit2:retrofit:2.0.2'

首先Builder(),得到OkHttpClient.Builder对象builder

 OkHttpClient.Builder builder = new OkHttpClient.Builder();

Log信息拦截器

Debug可以看到,网络请求,打印Log信息,发布的时候就不需要这些log

1、添加依赖

app/build.gradle

 compile 'com.squareup.okhttp3:logging-interceptor:3.1.2'

2、Log信息拦截器

if (BuildConfig.DEBUG) {
// Log信息拦截器
HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
//设置 Debug Log 模式
builder.addInterceptor(loggingInterceptor);
}

缓存机制

无网络时,也能显示数据

File cacheFile = new File(DemoApplication.getContext().getExternalCacheDir(), "WuXiaolongCache");
Cache cache = new Cache(cacheFile, 1024 * 1024 * 50);
Interceptor cacheInterceptor = new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
if (!AppUtils.networkIsAvailable(DemoApplication.getContext())) {
request = request.newBuilder()
.cacheControl(CacheControl.FORCE_CACHE)
.build();
}
Response response = chain.proceed(request);
if (AppUtils.networkIsAvailable(DemoApplication.getContext())) {
int maxAge = 0;
// 有网络时 设置缓存超时时间0个小时
response.newBuilder()
.header("Cache-Control", "public, max-age=" + maxAge)
.removeHeader("WuXiaolong")// 清除头信息,因为服务器如果不支持,会返回一些干扰信息,不清除下面无法生效
.build();
} else {
// 无网络时,设置超时为4周
int maxStale = 60 * 60 * 24 * 28;
response.newBuilder()
.header("Cache-Control", "public, only-if-cached, max-stale=" + maxStale)
.removeHeader("nyn")
.build();
}
return response;
}
};
builder.cache(cache).addInterceptor(cacheInterceptor);

公共参数

可能接口有某些参数是公共的,不可能一个个接口都去加吧

//公共参数
Interceptor addQueryParameterInterceptor = new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request originalRequest = chain.request();
Request request;
String method = originalRequest.method();
Headers headers = originalRequest.headers();
HttpUrl modifiedUrl = originalRequest.url().newBuilder()
// Provide your custom parameter here
.addQueryParameter("platform", "android")
.addQueryParameter("version", "1.0.0")
.build();
request = originalRequest.newBuilder().url(modifiedUrl).build();
return chain.proceed(request);
}
};
//公共参数
builder.addInterceptor(addQueryParameterInterceptor);

设置头

有的接口可能对请求头要设置

Interceptor headerInterceptor = new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request originalRequest = chain.request();
Request.Builder requestBuilder = originalRequest.newBuilder()
.header("AppType", "TPOS")
.header("Content-Type", "application/json")
.header("Accept", "application/json")
.method(originalRequest.method(), originalRequest.body());
Request request = requestBuilder.build();
return chain.proceed(request);
}
};
//设置头
builder.addInterceptor(headerInterceptor );

设置cookie

服务端可能需要保持请求是同一个cookie,主要看各自需求

1、app/build.gradle

 compile 'com.squareup.okhttp3:okhttp-urlconnection:3.2.0'

2、设置cookie

CookieManager cookieManager = new CookieManager();
cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
builder.cookieJar(new JavaNetCookieJar(cookieManager));

设置超时和重连

希望超时时能重连

 //设置超时
builder.connectTimeout(15, TimeUnit.SECONDS);
builder.readTimeout(20, TimeUnit.SECONDS);
builder.writeTimeout(20, TimeUnit.SECONDS);
//错误重连
builder.retryOnConnectionFailure(true);

最后将这些配置设置给retrofit:

OkHttpClient okHttpClient = builder.build();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(ApiStores.API_SERVER_URL)
//设置 Json 转换器
.addConverterFactory(GsonConverterFactory.create())
//RxJava 适配器
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.client(okHttpClient)
.build();

完整配置

public class AppClient {
public static Retrofit retrofit = null; public static Retrofit retrofit() {
if (retrofit == null) {
OkHttpClient.Builder builder = new OkHttpClient.Builder();
/**
*设置缓存,代码略
*/ /**
* 公共参数,代码略
*/ /**
* 设置头,代码略
*/ /**
* Log信息拦截器,代码略
*/ /**
* 设置cookie,代码略
*/ /**
* 设置超时和重连,代码略
*/ //以上设置结束,才能build(),不然设置白搭
OkHttpClient okHttpClient = builder.build(); retrofit = new Retrofit.Builder()
.baseUrl(ApiStores.API_SERVER_URL)
.client(okHttpClient)
.build();
}
return retrofit; }
}

接口参数

Path

类似这样链接:http://wuxiaolong.me/2016/01/15/retrofit/

 @GET("2016/01/15/{retrofit}")
Call<ResponseBody> getData(@Path("retrofit") String retrofit);

即您传的参数retrofit内容会替换大括号里的内容。

Query

类似这样链接:http://wuxiaolong.me/v1?ip=202.202.33.33&name=WuXiaolong

@GET("v1")
Call<ResponseBody> getData(@Query("ip") String ip,@Query("name") String name);

Field

表单提交,如登录

 @FormUrlEncoded
@POST("v1/login")
Call<ResponseBody> userLogin(@Field("phone") String phone, @Field("password") String password);

传json格式

如果参数是json格式,如:

{
"apiInfo": {
"apiName": "WuXiaolong",
"apiKey": "666"
}
}

建立Bean

 public class ApiInfo {
private ApiInfoBean apiInfo; public ApiInfoBean getApiInfo() {
return apiInfo;
} public void setApiInfo(ApiInfoBean apiInfo) {
this.apiInfo = apiInfo;
} public class ApiInfoBean {
private String apiName;
private String apiKey;
//省略get和set方法
}
}

ApiStores

@POST("client/shipper/getCarType")
Call<ResponseBody> getData(@Body ApiInfo apiInfo);

代码调用

ApiInfo apiInfo = new ApiInfo();
ApiInfo.ApiInfoBean apiInfoBean = apiInfo.new ApiInfoBean();
apiInfoBean.setApiKey("666");
apiInfoBean.setApiName("WuXiaolong");
apiInfo.setApiInfo(apiInfoBean);
//调接口
getData(apiInfo);

传数组

@GET("v1/enterprise/find")
Call<ResponseBody> getData(@Query("id") String id, @Query("linked[]") String... linked);

代码调用

String id="WuXiaolong";
String[] s = new String[]{"WuXiaolong"};
//调接口
getData(id, s);

传文件-单个

@Multipart
@POST("v1/create")
Call<ResponseBody> create(@Part("pictureName") RequestBody pictureName, @Part MultipartBody.Part picture);

代码调用

RequestBody pictureNameBody = RequestBody.create(MediaType.parse(AppConstants.CONTENT_TYPE_FILE), "pictureName");
File picture= new File(path);
RequestBody requestFile = RequestBody.create(MediaType.parse(AppConstants.CONTENT_TYPE_FILE), picture);
// MultipartBody.Part is used to send also the actual file name
MultipartBody.Part picturePart = MultipartBody.Part.createFormData("picture", picture.getName(), requestFile);
//调接口
create(pictureNameBody, picturePart);

传文件-多个

@Multipart
@POST("v1/create")
Call<ResponseBody> create(@Part("pictureName") RequestBody pictureName, @PartMap Map<String, RequestBody> params);

代码调用

RequestBody pictureNameBody = RequestBody.create(MediaType.parse(AppConstants.CONTENT_TYPE_FILE), "pictureName");
File picture= new File(path);
RequestBody requestFile = RequestBody.create(MediaType.parse(AppConstants.CONTENT_TYPE_FILE), picture);
Map<String, RequestBody> params = new HashMap<>();
params.put("picture\"; filename=\"" + picture.getName() + "", requestFile);
//调接口
create(pictureNameBody, params);

微信公众号

欢迎微信扫一扫关注:不止于技术分享,每天进步一点点。

关于作者

点击查看

Android Retrofit 2.0 使用-补充篇的更多相关文章

  1. android -------- Retrofit + RxJava2.0 + Kotlin + MVP 开发的 WanAndroid 项目

    简介 wanandroid项目基于 Retrofit + RxJava2.0 + Kotlin + MVP 用到的依赖 implementation 'io.reactivex.rxjava2:rxj ...

  2. Android Retrofit 2.0使用

    实例带你了解Retrofit 2.0的使用,分享目前开发Retrofit遇到的坑和心得. 添加依赖 app/build.gradle 1 compile 'com.squareup.retrofit2 ...

  3. Android Retrofit 2.0文件上传

    Android Retrofit 实现(图文上传)文字(参数)和多张图片一起上传 使用Retrofit进行文件上传,肯定离不开Part & PartMap. public interface ...

  4. Android - Retrofit 2.0 使用教程(含实例讲解)

    链接:https://blog.csdn.net/carson_ho/article/details/73732076

  5. Android:手把手带你深入剖析 Retrofit 2.0 源码

    前言 在Andrroid开发中,网络请求十分常用 而在Android网络请求库中,Retrofit是当下最热的一个网络请求库 今天,我将手把手带你深入剖析Retrofit v2.0的源码,希望你们会喜 ...

  6. Android UI开发第四十三篇——使用Property Animation实现墨迹天气3.0引导界面及动画实现

    前面写过<墨迹天气3.0引导界面及动画实现>,里面完美实现了动画效果,那一篇文章使用的View Animation,这一篇文章使用的Property Animation实现.Propert ...

  7. Retrofit全攻略——基础篇

    实际开发过程中一般都会选择一些网络框架提升开发效率.随着Google对HttpClient 摒弃和Volley框架的逐渐没落.OkHttp開始异军突起.而Retrofit则对OkHttp进行了强制依赖 ...

  8. 从零开始的Android新项目1 - 架构搭建篇

    记录一下新项目的搭建. 试想一下,如果没有历史负担,没有KPI压力,去新搭建一个项目,你会怎么设计和实现呢? 本系列文章不是教你怎么从0开始学Android,从0开始怎么建一个项目,而定位于零负担的情 ...

  9. Retrofit 2.0 超能实践(四),完成大文件断点下载

    作者:码小白 文/CSDN 博客 本文出自:http://blog.csdn.net/sk719887916/article/details/51988507 码小白 通过前几篇系统的介绍和综合运用, ...

随机推荐

  1. opencv在图像显示中文

    在图像定位和模式识别时,经常需要把结果标注到图片上,标注内容可以是数字字母.矩形框等(opencv支持的)或者是中文汉字(借助freetype). 1.显示数字/矩形框 #include <op ...

  2. MIP开发常见问题解答

    校验相关 1. MIP 页面的 <a>链接校验报错,MIP 是强制 target="_blank" 吗? 如果想直接跳转MIP页,可以用mip-link 组件:MIP ...

  3. iOS开源项目周报0105

    由OpenDigg 出品的iOS开源项目周报第四期来啦.我们的iOS开源周报集合了OpenDigg一周来新收录的优质的iOS开发方面的开源项目,方便iOS开发人员便捷的找到自己需要的项目工具等. He ...

  4. C#基础篇 - 正则表达式入门

    1.基本概念 正则表达式(Regular Expression)就是用事先定义好的一些特定字符(元字符)或普通字符.及这些字符的组合,组成一个“规则字符串”,这个“规则字符串”用来判断我们给定的字符串 ...

  5. WebForm获取GET或者POST参数到实体的转换,ADO.NET数据集自动转换实体

    最近在修改维护以前的webform项目(维护别人开发的.....)整个aspx没有用到任何的控件,这个我也比较喜欢不用控件所以在提交信息的时候需要自己手动的去Request.QueryString[] ...

  6. vue双向数据绑定原理探究(附demo)

    昨天被导师叫去研究了一下vue的双向数据绑定原理...本来以为原理的东西都非常高深,没想到vue的双向绑定真的很好理解啊...自己动手写了一个. 传送门 双向绑定的思想 双向数据绑定的思想就是数据层与 ...

  7. 【腾讯Bugly干货分享】Android Linker 与 SO 加壳技术

    本文来自于腾讯bugly开发者社区,非经作者同意,请勿转载,原文地址:http://dev.qq.com/topic/57e3a3bc42eb88da6d4be143 作者:王赛 1. 前言 Andr ...

  8. java常用的设计模式

    设计模式:一个程序员对设计模式的理解:"不懂"为什么要把很简单的东西搞得那么复杂.后来随着软件开发经验的增加才开始明白我所看到的"复杂"恰恰就是设计模式的精髓所 ...

  9. 嵌入式C语言代码的调试技巧

    在项目开发的过程中,不可避免的会遇到调试代码的情况. 刚开始写代码时,我们想看具体执行到哪儿时,往往这么写: printf("***** Code is here! *****\n" ...

  10. BZOJ 3083: 遥远的国度 [树链剖分 DFS序 LCA]

    3083: 遥远的国度 Time Limit: 10 Sec  Memory Limit: 1280 MBSubmit: 3127  Solved: 795[Submit][Status][Discu ...