android retrofit 2.0公共参数,Android Retrofit 2.0 使用-补充篇
之前分享的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
@GET("2016/01/15/{retrofit}")
Call getData(@Path("retrofit") String retrofit);
即您传的参数retrofit内容会替换大括号里的内容。
Query
@GET("v1")
Call getData(@Query("ip") String ip,@Query("name") String name);
Field
表单提交,如登录
@FormUrlEncoded
@POST("v1/login")
Call 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 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 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 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 create(@Part("pictureName") RequestBody pictureName, @PartMap Map 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 params = new HashMap<>();
params.put("picture\"; filename=\"" + picture.getName() + "", requestFile);
//调接口
create(pictureNameBody, params);
微信公众号
我的微信公众号:吴小龙同学。
不止于技术分享,不取悦他人,写给懂的你看~
欢迎微信扫一扫关注。
android retrofit 2.0公共参数,Android Retrofit 2.0 使用-补充篇相关推荐
- android retrofit 2.0公共参数,Retrofit2.0 添加公共参数
//这里可以添加公共参数 Interceptor addQueryParameterInterceptor = new Interceptor() { @Override public Respons ...
- android post请求添加公共参数_XHttp2 一个功能强悍的网络请求库
XHttp2 一个功能强悍的网络请求库,使用RxJava2 + Retrofit2 + OKHttp组合进行封装.还不赶紧点击使用说明文档,体验一下吧! 项目地址 关于我 https://github ...
- android post请求添加公共参数_Java实现通用的Get和Post请求组件
开发中经常遇到发送一个远程请求并解析返回结果的情况,那可以在项目中写一个Get/Post的组件,以后遇到远程请求直接调用即可 实现步骤为: 1.创建一个URL(java.net.URL)对象 2.打开 ...
- android是什么牌手机参数,Android 获取手机品牌、型号等信息
利用Build类,通过反射可以获得全部fields里的key和value. Field[] fields = Build.class.getFields(); for (Field f : field ...
- Android:手把手带你深入剖析 Retrofit 2.0 源码
前言 在Andrroid开发中,网络请求十分常用 而在Android网络请求库中,Retrofit是当下最热的一个网络请求库 今天,我将手把手带你深入剖析Retrofit v2.0的源码,希望你们会喜 ...
- 0.高仿Android网易云音乐OkHttp+Retrofit+RxJava+Glide+MVC+MVVM
0.系列文章目录 1.启动界面 2.广告和引导界面 1.项目简介 这是一个使用Java(以后还会推出Kotlin版本)语言,从0开发一个Android平台,接近企业级的项目(我的云音乐),包含了基础内 ...
- Android 教你一步步搭建MVP+Retrofit+RxJava网络请求框架
目录 1.什么是MVP? 2.什么是Retrofit? 3.RxJava 4.实践 之前公司的项目用到了MVP+Retrofit+RxJava的框架进行网络请求,所以今天特此写一篇文章以做总结.相信很 ...
- 第一行代码 第三版 第11章网络技术 11.6.1 Retrofit 应用 报错:android.system.ErrnoException: isConnected failed: ECONNRE
在学习第11章 11.6.1Retrofit用法,这节的时候发生的报错:书上关于这个地方并没有说. 我搜索问题的关键语句是: java.net.ConnectException: Failed to ...
- Android高仿网易云音乐OkHttp+Retrofit+RxJava+Glide+MVC+MVVM
简介 这是一个使用Java(以后还会推出Kotlin版本)语言,从0开发一个Android平台,接近企业级的项目(我的云音乐),包含了基础内容,高级内容,项目封装,项目重构等知识:主要是使用系统功能, ...
最新文章
- 小米6关闭位置服务器,关闭这6个设置,让你的小米手机从回青春,再战3年
- Mac上安装hadoop
- 编程之美-从无头单链表中删除节点方法整理
- 名品折扣,谁与争锋!
- 莫利定理的超直观演示!
- oracle em agent,ORACLE 11G EM 配置命令及问题处理
- 01_jeecms建站
- PAI通过流式机器学习算法解决实时热点新闻挖掘案例
- 腾讯游戏与NVIDIA合作发布START云游戏服务
- linux服务器u盘启动项检测不到,将U盘设置为第一启动项之后却检测不到U盘怎么办?...
- notification源码分析_Ceilometer之notification agent代码分析
- python乘法运算为什么是重复_警惕python中的*重复符(运算符)
- 你这几天因为 YYYY-MM-dd 被提 BUG 了吗??
- java截取视频的帧
- java流和循环 效率_Java stream 和 for循环效率对比问题
- visio和preject冲突_我平时用Project和visio,WPS能代替嘛?
- 【Stream流学习】Java 8 新特性|Collectors.joining() 案例详解
- 如何爬虫同花顺概念数据?pyppeteer
- C++:Error C 1010:在查找预编译头时遇到意外的文件结尾。
- Simulink Simscape基础仿真电路
热门文章
- openstack核心组件-nova-计算服务
- Facebook 平台详解
- <input type=“file“>实现上传文件
- 基于JAVA中学生作文大赛管理平台计算机毕业设计源码+系统+数据库+lw文档+部署
- openlayers地图旋转_OpenLayers 3 之 地图视图(View)
- macdown code编辑不能换行的问题
- 200台PS3可破解MD5加密算法 安全网页不再安全
- c语言unicode编码转ascii码,Unicode和ASCII的转换
- 接第一篇博客:fw的第二场CTF——HECTF2021 WP
- 改善顶推施工方法带来的负面影响可以采取哪些措施。