package com.android.app_base.http; import androidx.collection.CircularArray; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.TypeAdapter; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonToken; import com.google.gson.stream.JsonWriter; import java.util.HashMap; import java.util.Map; import okhttp3.Interceptor; import okhttp3.OkHttpClient; import retrofit2.Retrofit; import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory; import retrofit2.converter.gson.GsonConverterFactory; /** * @author Ljj * @date 2023.03.02. 14:11 * @desc Retrofit管理,可以有不同的 baseUrl */ public class RetrofitManager { private static volatile RetrofitManager instance; private final Map retrofitMap; private OkHttpClient mClient; public static RetrofitManager getInstance(){ if (instance == null) { synchronized (RetrofitManager.class) { if (instance == null) { instance = new RetrofitManager(); } } } return instance; } private RetrofitManager(){ retrofitMap = new HashMap<>(); mClient = OkHttpHelper.getOkHttpClient(); } /** * 获取Retrofit对象 */ public Retrofit getRetrofit(String baseUrl) { Gson gson = new GsonBuilder() //配置你的Gson .setDateFormat("yyyy-MM-dd hh:mm:ss") .registerTypeHierarchyAdapter(String.class,STRING)//设置解析的时候null转成"" .create(); Retrofit retrofit = retrofitMap.get(baseUrl); if (retrofit == null) { retrofit = new Retrofit.Builder() .client(mClient) .addConverterFactory(GsonConverterFactory.create(gson)) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .baseUrl(baseUrl) .build(); retrofitMap.put(baseUrl, retrofit); } return retrofit; } /** * 自定义TypeAdapter ,null对象将被解析成空字符串 */ public static final TypeAdapter STRING = new TypeAdapter() { public String read(JsonReader reader) { try { if (reader.peek() == JsonToken.NULL) { reader.nextNull(); return ""; // 原先是返回null,这里改为返回空字符串 } return reader.nextString(); } catch (Exception e) { e.printStackTrace(); } return ""; } public void write(JsonWriter writer, String value) { try { if (value == null) { writer.nullValue(); return; } writer.value(value); } catch (Exception e) { e.printStackTrace(); } } }; /** * 设置 自定义OkHttpClient */ public RetrofitManager setOkHttpClient(OkHttpClient client) { this.mClient = client; return instance; } }