使用Retrofit,后台返回的cookie值该怎么拿到呢?

202005021116 应用层 2019-06-19 07:36:22
返回的值控制台是这样打印的: OkHttp: Set-Cookie: JSESSIONID=54751703-2d8a-4f15-969e-34b5edc05017; Path=/; HttpOnly
也就是JSESSIONID=后面的就是cookie.
后台想要我登陆成功后保存这个返回的cookie,然后每次登陆都传这个cookie过去.现在的问题是:登陆成功后怎么拿到这个cookie值,然后每次传的时候怎么带过去?
下面是Retrofit的封装类:
public class RxManager {

private static RxManager INSTANCE;
private RequestMethod mRequestService;
private Gson mGson = new Gson();
//使用cookie保存用户状态
private MediaType JSON = MediaType.parse("application/json; charset=utf-8");
private static WeakReference<Activity> mActivity;
private static final String TAG = "RxManager";

private RxManager() {
OkHttpClient okHttpClient = createOkHttpClient();
Retrofit retrofit = new Retrofit.Builder().baseUrl(RequestUrl.BASE_URL)
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create(mGson))
// .addConverterFactory(ResponseConverterFactory.create(mGson)) //处理Rxjava、Retrofit返回json数据解析异常
.client(okHttpClient)
.build();
mRequestService = retrofit.create(RequestMethod.class);
}

public static RxManager getInstance() {
if (INSTANCE == null) {
INSTANCE = new RxManager();
}
return INSTANCE;
}

private OkHttpClient createOkHttpClient() {
// cookieJar.clear();
// Log.d(TAG, "createOkHttpClient: 1709= "+cookieJar.toString());

HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY); //这行必须加 不然默认不打印
//cache url
File httpCacheDirectory = new File(BaseApplication.getContext().getCacheDir(), "responses");
int cacheSize = 10 * 1024 * 1024; // 10 MiB
Cache cache = new Cache(httpCacheDirectory, cacheSize);

SharedPrefsCookiePersistor sharedPrefsCookiePersistor = new SharedPrefsCookiePersistor(BaseApplication.getContext());
List<Cookie> cookies = sharedPrefsCookiePersistor.loadAll();
for (int i = 0; i < cookies.size(); i++) {
Cookie cookie = cookies.get(i);
Log.d(TAG, "createOkHttpClient: 1810="+cookie.name()+" "+cookie.value());
}
ClearableCookieJar cookieJar = new PersistentCookieJar(new SetCookieCache(), sharedPrefsCookiePersistor);

return new OkHttpClient
.Builder()
.cookieJar(cookieJar) //使用cookie保存用户状态
.cache(new Cache(BaseApplication.getContext().getCacheDir(), 1024 * 1024 * 100))
.connectTimeout(30, TimeUnit.SECONDS)
.readTimeout(30, TimeUnit.SECONDS)
.writeTimeout(30, TimeUnit.SECONDS)
.addInterceptor(loggingInterceptor) //添加控制台网络请求消息拦截器,直接在控制台输出
.cache(cache)
.addInterceptor(REWRITE_CACHE_CONTROL_INTERCEPTOR)
// .addInterceptor(new CacheInterceptor(BaseApplication.getContext().getCacheDir().getAbsolutePath()))
.addInterceptor(chain -> {
Request request = chain.request();
Response response = chain.proceed(request);
int code = response.code();
Log.d(TAG, " 0922: OkHttpClient 内code=OkHttpClient " + code);

if (code == 200) {
if (null != response.header("Set-Cookie")) {
String cookie = response.header("Set-Cookie").split(";")[0];
Log.d(TAG, "createOkHttpClient: 1917= "+cookie);// 这里的cookie打印的是 rememberMe=deleteMe,应该不对
}
}
return response;
}).build();
}

//cache
Interceptor REWRITE_CACHE_CONTROL_INTERCEPTOR = chain -> {
CacheControl.Builder cacheBuilder = new CacheControl.Builder();
cacheBuilder.maxAge(0, TimeUnit.SECONDS);
cacheBuilder.maxStale(365, TimeUnit.DAYS);
CacheControl cacheControl = cacheBuilder.build();
Request request = chain.request();
if (!NetWorkStatusUtil.checkNetWorkAvaliable(BaseApplication.getContext())) {
request = request.newBuilder()
.cacheControl(cacheControl)
.build();
}
Response originalResponse = chain.proceed(request);
int code = originalResponse.code();

Log.d(TAG, " 0922: 拦截器内code= " + code);
//todo: 302直接到未登录主页
if (code == 302) {
UserManager.getInstance().logout();//清除所有数据
PreferenceUtil.clearSingle(mActivity.get(), "assessment");
ToastUtils.showShort(R.string.please_relogin);
Intent loginIntent = new Intent(mActivity.get(), UnloginMainActivity.class);
loginIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
mActivity.get().startActivity(loginIntent);
}

if (NetWorkStatusUtil.checkNetWorkAvaliable(BaseApplication.getContext())) {
int maxAge = 0; // read from cache
return originalResponse.newBuilder()
.removeHeader("Pragma")
.header("Cache-Control", "public ,max-age=" + maxAge)
.build();
} else {
int maxStale = 60 * 60 * 24 * 28; // tolerate 4-weeks stale
return originalResponse.newBuilder()
.removeHeader("Pragma")
.header("Cache-Control", "public, only-if-cached, max-stale=" + maxStale)
.build();
}
};

private RequestMethod getRequestMethod() {
return mRequestService;
}

public static RequestMethod getMethod() {
return getInstance().getRequestMethod();
}

public static RequestMethod getMethod(Activity activity) {
mActivity = new WeakReference<>(activity);
return getInstance().getRequestMethod();
}
}
...全文
262 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
展翼翔宇 2019-06-25
  • 打赏
  • 举报
回复
自定义一个cookie的类,在OkHttpClient 有一个cookieJar,用这个去添加cookie就行

80,351

社区成员

发帖
与我相关
我的任务
社区描述
移动平台 Android
androidandroid-studioandroidx 技术论坛(原bbs)
社区管理员
  • Android
  • yechaoa
  • 失落夏天
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧