Retrofit

Retrofit 增加Cookie

1.建立公共的Application類

public class MyApplication extends Application {
    @SuppressLint("StaticFieldLeak")
    private static Context context;

    @Override
    public void onCreate() {
        super.onCreate();
        context = getApplicationContext();
    }

    public static Context getContext() {
        return context;
    }
}

2.在第一次登入把Response回傳的Cookie存起來

登入回傳的onResponse

 HashSet<String> cookies = new HashSet<>();
 cookies.add(response.headers().get("Set-Cookie"));
 SharedPreferences.Editor config = act.getSharedPreferences("config", MODE_PRIVATE).edit();
 config.putStringSet("cookie", cookies);
 config.apply();

3.未來調用 新增一個類別 實現Interceptor

public class AddCookiesInterceptor implements Interceptor {

    @NonNull
    @Override
    public Response intercept(Chain chain) throws IOException {
        Request.Builder builder = chain.request().newBuilder();
        HashSet preferences = (HashSet) MyApplication.getContext().getSharedPreferences("config",
                Context.MODE_PRIVATE).getStringSet("cookie", null);
        if (preferences != null) {
            for (Object cookie : preferences) {
                builder.addHeader("Cookie", String.valueOf(cookie));
            }
        }
        return chain.proceed(builder.build());
    }
}

4.RetrofitUtils

public class RetrofitUtils {
    public static Retrofit getInstance() {

        //保存cookie
        OkHttpClient client = new OkHttpClient.Builder()
                .addInterceptor(new AddCookiesInterceptor())
                .build();

        Retrofit build = new Retrofit.Builder()
                .baseUrl("url") //Server URL
                .client(client)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        return build;
    }
}

發表迴響