27
22

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

OkHttpでCookieを扱う

Last updated at Posted at 2015-05-13

OkHttpを使用していて、Cookieの取り扱いに困ったのでメモ。
自動でやってくれるとおもいきや動かなかったので困った。

OkHttpClientはシングルトンにして使いまわしたほうが良いとのことだったので
Applicationで生成時にCookieManagerを追加しておく。

MyApplication.java
public class MyApplication extends Application{
    private static final String TAG = MyApplication.class.getSimpleName();
    private static MyApplication MY_APPRICATION;
    private static Context sContext;

    private OkHttpClient mOkHttpClient;

    public static MyApplication getInstance(){
        if(MY_APPRICATION == null){
            MY_APPRICATION = new MyApplication();
            MY_APPRICATION.setOkhttpClient();
        }

        return MY_APPRICATION;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        sContext = getApplicationContext();
        MY_APPRICATION = new MyApplication();

        Stetho.initialize(
                Stetho.newInitializerBuilder(this)
                        .enableDumpapp(
                                Stetho.defaultDumperPluginsProvider(this))
                        .enableWebKitInspector(
                                Stetho.defaultInspectorModulesProvider(this))
                        .build());

}

    public Context getsContext(){
        if(sContext == null){
            sContext = getApplicationContext();
        }
        return sContext;
    }

    public OkHttpClient getOkhttpClient(){
        if(mOkHttpClient == null){
            setOkhttpClient();
        }
        return mOkHttpClient;
    }

    private void setOkhttpClient(){
        mOkHttpClient = new OkHttpClient();
        mOkHttpClient.networkInterceptors().add(new StethoInterceptor());

        // enable cookies
        java.net.CookieManager cookieManager = new java.net.CookieManager();
        cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
        CookieHandler.setDefault(cookieManager);
        mOkHttpClient.setCookieHandler(cookieManager);
    }
}

##参考URL
http://qiita.com/ryugoo/items/d287c474b9dc20dae959

27
22
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
27
22

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?