RetrofitUtils的工具类
直接上代码 ,一个RetrofitFactory,一个ApiFactory
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58package com.aidebar.retrofitutils.Utils.RetrofitUtils;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
/**
* @author xzj
* @date 2016/8/25 09:37.
* 用于获取配置好的retrofit对象
* 需要先调用setBaseUrl,如果项目中BaseUrl不变,可以写死
*/
public class RetrofitFactory {
private static Retrofit retrofit;
private static String baseUrl;
public static void setBaseUrl(String url) {
baseUrl = url;
}
/**
* 获取配置好的retrofit对象来生产Manager对象
*/
public static Retrofit getRetrofit() {
if (retrofit == null) {
if (baseUrl == null || baseUrl.length() <= 0)
throw new IllegalStateException("请在调用getFactory之前先调用setBaseUrl");
Retrofit.Builder builder = new Retrofit.Builder();
builder.baseUrl(baseUrl)
.addCallAdapterFactory(RxJavaCallAdapterFactory.create()) // 参考RxJava
.addConverterFactory(GsonConverterFactory.create()); // 参考与GSON的结合
// 参考自定义Log输出
OkHttpClient client = new OkHttpClient().newBuilder()
// .addInterceptor(new Interceptor() { //这个拦截器是操作请求头的
// @Override
// public Response intercept(Chain chain) throws IOException {
// Request request = chain.request().newBuilder()
// .addHeader("version", "123411") //这里就是添加一个请求头
// .build();
//
//// Buffer buffer = new Buffer(); 不依赖下面的Interceptor,用这三行也能打印出请求体
//// request.body().writeTo(buffer);
//// Log.d(getClass().getSimpleName(), "intercept: " + buffer.readUtf8());
//
// return chain.proceed(request);
// }
// })
// .addInterceptor(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY)) //这个拦截器是用来打印日志的,不稳定
.build();
builder.client(client);
retrofit = builder.build();
}
return retrofit;
}
}1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32package com.aidebar.retrofitutils.Utils.RetrofitUtils;
import java.util.HashMap;
/**
* @author xzj
* @date 2016/8/25 09:38.
* 通过定义好的api接口以及Retrofit来生成具体的实例.
*/
public class ApiFactory {
private static ApiFactory factory;
private static HashMap<String, Object> serviceMap = new HashMap<>();
public static ApiFactory getFactory() {
if (factory == null) {
synchronized (ApiFactory.class) {
if (factory == null)
factory = new ApiFactory();
}
}
return factory;
}
public <T> T create(Class<T> clz) {
Object service = serviceMap.get(clz.getName());
if (service == null) {
service = RetrofitFactory.getRetrofit().create(clz);
serviceMap.put(clz.getName(), service);
}
return (T) service;
}
}
还有2个是用rxjava进行配合的可以选用
1 | package com.aidebar.retrofitutils.Utils.RetrofitUtils; |
本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 七夜的小屋!