创建SpUtils
package jiaoyibo.bawei.com.retrofitdenglu.net;
import android.content.Context;
import android.content.SharedPreferences;
public class SpUtils {
private static final String FILE_NAME = "user";
private static SharedPreferences mSharedPreferences;// 单例
private static SpUtils instance;// 单例
private SpUtils(Context context) {
mSharedPreferences = context.getSharedPreferences(FILE_NAME,
Context.MODE_PRIVATE);
}
/**
* 初始化单例
* @param context
*/
public static synchronized void init(Context context) {
if (instance == null) {
instance = new SpUtils(context);
}
}
/**
* 获取单例
*
* @return
*/
public static SpUtils getInstance() {
if (instance == null) {
throw new RuntimeException("class should init!");
}
return instance;
}
/**
* 保存数据
*
* @param key
* @param data
*/
public void saveData(String key, Object data) {
String type = data.getClass().getSimpleName();
SharedPreferences.Editor editor = mSharedPreferences.edit();
if ("Integer".equals(type)) {
editor.putInt(key, (Integer) data);
} else if ("Boolean".equals(type)) {
editor.putBoolean(key, (Boolean) data);
} else if ("String".equals(type)) {
editor.putString(key, (String) data);
} else if ("Float".equals(type)) {
editor.putFloat(key, (Float) data);
} else if ("Long".equals(type)) {
editor.putLong(key, (Long) data);
}
editor.commit();
}
/**
* 得到数据
*
* @param key
* @param defValue
* @return
*/
public Object getData(String key, Object defValue) {
String type = defValue.getClass().getSimpleName();
if ("Integer".equals(type)) {
return mSharedPreferences.getInt(key, (Integer) defValue);
} else if ("Boolean".equals(type)) {
return mSharedPreferences.getBoolean(key, (Boolean) defValue);
} else if ("String".equals(type)) {
return mSharedPreferences.getString(key, (String) defValue);
} else if ("Float".equals(type)) {
return mSharedPreferences.getFloat(key, (Float) defValue);
} else if ("Long".equals(type)) {
return mSharedPreferences.getLong(key, (Long) defValue);
}
return null;
}
}
创建QinqiuUtils
package jiaoyibo.bawei.com.retrofitdenglu.net;
import java.io.IOException;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
public class QinqiuUtils implements Interceptor {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
Object userId = SpUtils.getInstance().getData("userId", "");
Object sessionId = SpUtils.getInstance().getData("sessionId", "");
Request.Builder builder = request.newBuilder();
builder.addHeader("userId", (String) userId);
builder .addHeader("sessionId", (String) sessionId);
Request build = builder.build();
Response C = chain.proceed(build);
return C;
}
}
记得app初始化
SpUtils.init(getApplicationContext());
在工具类里OkHttpClient里添加
.addInterceptor(new QinqiuUtils())
登录成功方法调用
SpUtils.getInstance().saveData("userId",loginBean.getResult().getUserId()+"");
SpUtils.getInstance().saveData("sessionId",loginBean.getResult().getSessionId()+"");