- import android.os.Environment;
- import java.io.File;
- import java.io.IOException;
- import java.util.concurrent.TimeUnit;
- import okhttp3.FormBody;
- import okhttp3.Interceptor;
- import okhttp3.OkHttpClient;
- import okhttp3.Request;
- import okhttp3.RequestBody;
- import okhttp3.Response;
- import okhttp3.logging.HttpLoggingInterceptor;
- import retrofit2.Retrofit;
- import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
- import retrofit2.converter.gson.GsonConverterFactory;
- /**
- * 网络请求工具类
- */
- public class RetrofitUtil {
- private static RetrofitUtil retrofitUtil;//工具类对象
- private static RetrofitService retrofitService;//请求网络接口
- public static OkHttpClient okHttpClient;
- //静态快,获取OkHttpClient对象
- static {
- getOkHttpClient();
- }
- //单例锁模式
- public static RetrofitUtil getInstence() {
- if (retrofitUtil == null) {
- synchronized (RetrofitUtil.class) {
- if (retrofitUtil == null) {
- retrofitUtil = new RetrofitUtil();
- }
- }
- }
- return retrofitUtil;
- }
- //单例模式获取okhttp
- public static OkHttpClient getOkHttpClient() {
- if (okHttpClient == null) {
- synchronized (OkHttpClient.class) {
- if (okHttpClient == null) {
- File fileDir = new File(Environment.getExternalStorageDirectory(), "cache");
- long fileSize = 10 * 1024 * 1024;
- okHttpClient = new OkHttpClient.Builder()
- .addInterceptor(new RetrofitIntercepter())
- //打印拦截器日志
- .addNetworkInterceptor(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY))
- .connectTimeout(15, TimeUnit.SECONDS)//设置连接超时时间
- .readTimeout(15, TimeUnit.SECONDS)//设置读取超时时间
- .writeTimeout(15, TimeUnit.SECONDS)//设置写入超时时间
- //.cache(new Cache(fileDir,fileSize))//写入sd卡
- .build();
- }
- }
- }
- return okHttpClient;
- }
- //私有的无参构造
- private RetrofitUtil() {
- Retrofit retrofit = new Retrofit.Builder()
- .baseUrl(HttpConfig.baseUrl)
- .addConverterFactory(GsonConverterFactory.create())//添加gson转换器
- .addCallAdapterFactory(RxJava2CallAdapterFactory.create())//添加rxjava转换器
- .client(okHttpClient)//添加okhttp
- .build();
- retrofitService = retrofit.create(RetrofitService.class);
- }
- //拦截器
- static class RetrofitIntercepter implements Interceptor {
- @Override
- public Response intercept(Chain chain) throws IOException {
- Request request = chain.request();
- RequestBody body = request.body();
- if (body instanceof FormBody) {
- FormBody.Builder builder = new FormBody.Builder();
- for (int i = 0; i < ((FormBody) body).size(); i++) {
- String key = ((FormBody) body).name(i);
- String value = ((FormBody) body).value(i);
- builder.add(key, value);
- }
- builder.add("source", "android");//appVersion=101
- builder.add("appVersion", "101");
- FormBody formBody = builder.build();
- Request request1 = request.newBuilder().post(formBody).build();
- Response response = chain.proceed(request1);
- return response;
- }
- return null;
- }
- }
- //获取
- public RetrofitService API() {
- return retrofitService;
- }
- }
Retrofit的网络封装
最新推荐文章于 2022-08-12 20:16:37 发布