封装Retrofit进行网络请求,因为收藏等接口需要保存Cookie才可以使用,所以结合MMKV进行Cookie保存。
MMKV封装
MMKV.initialize(this);
public class MmkvUtil {
private static MmkvUtil instance;
private MMKV mmkv;
public static MmkvUtil getInstance(){
if (instance == null){
instance = new MmkvUtil();
}
return instance;
}
public MmkvUtil() {
mmkv = MMKV.defaultMMKV();
}
public void setString(String key, String value) {
if (!isEmpty(key, value)) {
if (null == mmkv) {
mmkv = MMKV.defaultMMKV();
}
mmkv.encode(key, value);
}
}
public String getString(String key) {
if (null == key) {
return null;
}
if (null == mmkv) {
mmkv = MMKV.defaultMMKV();
}
return mmkv.decodeString(key, "");
}
public String getTimeJiHuaString(String key) {
if (null == key) {
return null;
}
if (null == mmkv) {
mmkv = MMKV.defaultMMKV();
}
return mmkv.decodeString(key, "{}");
}
public String getString(String key, String str) {
if (null == key) {
return null;
}
if (null == mmkv) {
mmkv = MMKV.defaultMMKV();
}
return mmkv.decodeString(key, str);
}
public void setBoolean(String key, boolean value) {
if (null == key) {
return;
}
if (null == mmkv) {
mmkv = MMKV.defaultMMKV();
}
mmkv.encode(key, value);
}
public void setInt(String key, int value) {
if (null == key) {
return;
}
if (null == mmkv) {
mmkv = MMKV.defaultMMKV();
}
mmkv.encode(key, value);
}
public void setLong(String key, long value) {
if (null == key) {
return;
}
if (null == mmkv) {
mmkv = MMKV.defaultMMKV();
}
mmkv.encode(key, value);
}
public boolean getBoolean(String key) {
if (null == key) {
return false;
}
if (null == mmkv) {
mmkv = MMKV.defaultMMKV();
}
return mmkv.decodeBool(key, false);
}
public boolean getBooleanTrue(String key) {
if (null == key) {
return false;
}
if (null == mmkv) {
mmkv = MMKV.defaultMMKV();
}
return mmkv.decodeBool(key, true);
}
public int getInt(String key) {
if (null == key) {
return -1;
}
if (null == mmkv) {
mmkv = MMKV.defaultMMKV();
}
return mmkv.decodeInt(key, -1);
}
public int getIntK(String key) {
if (null == key) {
return 0;
}
if (null == mmkv) {
mmkv = MMKV.defaultMMKV();
}
return mmkv.decodeInt(key, 0);
}
public long getLong(String key) {
if (null == key) {
return -1;
}
if (null == mmkv) {
mmkv = MMKV.defaultMMKV();
}
return mmkv.decodeLong(key, -1);
}
public boolean setFloat(String key, float value) {
if (null == key) {
return false;
}
if (null == mmkv) {
mmkv = MMKV.defaultMMKV();
}
return mmkv.encode(key, value);
}
public float getFloat(String key) {
if (null == key || "".equals(key)) {
return 0;
}
if (null == mmkv) {
mmkv = MMKV.defaultMMKV();
}
assert mmkv != null;
if (!mmkv.contains(key)) {
return 0;
}
return mmkv.decodeFloat(key, 0);
}
public boolean setSet(String key, Set<String> data) {
if (null == key) {
return false;
}
if (null == mmkv) {
mmkv = MMKV.defaultMMKV();
}
return mmkv.encode(key, data);
}
public Set<String> getSet(String key) {
if (null == key || "".equals(key)) {
return null;
}
if (null == mmkv) {
mmkv = MMKV.defaultMMKV();
}
assert mmkv != null;
if (!mmkv.contains(key)) {
return null;
}
return mmkv.decodeStringSet(key);
}
private boolean isEmpty(String key, String value) {
if (null == key || null == value) {
return true;
}
return false;
}
public void clearAll() {
if (null == mmkv) {
mmkv = MMKV.defaultMMKV();
}
if (mmkv != null)
mmkv.clearAll();
mmkv = null;
}
public boolean removeKey(String key) {
if (mmkv.contains(key)) {
return mmkv.edit().remove(key).commit();
}
return false;
}
public boolean containsKey(String key) {
return mmkv.contains(key);
}
}
封装Retrofit
import com.jetpack.demo.common.Constant;
import com.jetpack.demo.util.MmkvUtil;
import com.tencent.mmkv.MMKV;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class RetrofitUtil {
public static final String BASE_URL = "https://www.wanandroid.com";
private static RetrofitUtil retrofitUtils;
private Retrofit mRetrofit;
private RetrofitUtil() {
}
public static RetrofitUtil getInstance() {
if (retrofitUtils == null) {
synchronized (RetrofitUtil.class) {
if (retrofitUtils == null) {
retrofitUtils = new RetrofitUtil();
}
}
}
return retrofitUtils;
}
public Retrofit createRetrofit() {
OkHttpClient.Builder builder = new OkHttpClient.Builder();
HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor();
httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient client = builder.addInterceptor(httpLoggingInterceptor)
.addInterceptor(new ReceivedCookiesInterceptor())
.addInterceptor(new AddCookiesInterceptor())
.readTimeout(10, TimeUnit.SECONDS)
.connectTimeout(10, TimeUnit.SECONDS)
.retryOnConnectionFailure(true).build();
mRetrofit =
new Retrofit.Builder().baseUrl(BASE_URL).addConverterFactory(GsonConverterFactory.create()).client(client).build();
return mRetrofit;
}
public Retrofit getRetrofit() {
if (mRetrofit == null){
mRetrofit = createRetrofit();
}
return mRetrofit;
}
public class ReceivedCookiesInterceptor implements Interceptor {
public ReceivedCookiesInterceptor() {
super();
}
@Override
public Response intercept(Chain chain) throws IOException {
Response originalResponse = chain.proceed(chain.request());
//这里获取请求返回的cookie
if (!originalResponse.headers("Set-Cookie").isEmpty()) {
Set<String> cookies = new HashSet<>();
for(String header: originalResponse.headers("Set-Cookie"))
{
cookies.add(header);
}
MmkvUtil.getInstance().setSet(Constant.MMKV_COOKIE_KEY,cookies);
}
return originalResponse;
}
}
public class AddCookiesInterceptor implements Interceptor {
@Override
public Response intercept(Chain chain) throws IOException {
Request.Builder builder = chain.request().newBuilder();
Set<String> cookie = MmkvUtil.getInstance().getSet(Constant.MMKV_COOKIE_KEY);
if (cookie != null) {
for (String c : cookie) {
builder.addHeader("Cookie", c);
}
}
return chain.proceed(builder.build());
}
}
}
请求实例
@GET("project/list/{pageId}/json")
Call<BaseResponse<ProjectListResponse>> getProjectList(@Path("pageId") int pageId, @Query("cid") int cid);
@FormUrlEncoded
@POST("user/login")
Call<BaseResponse<LoginResponse>> login (@Field("username") String username, @Field("password") String password);