回傳的值控制臺是這樣列印的: 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();
}
}
uj5u.com熱心網友回復:
自定義一個cookie的類,在OkHttpClient 有一個cookieJar,用這個去添加cookie就行轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/133438.html
標籤:Android
