首先在
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) {
}
});
请求结果: