読者です 読者をやめる 読者になる 読者になる

きょこみのーと

元六本木でGo書いてました。今はVRでGo書いてます。

AndroidのDefaultHttpClientでログインしたcookieをWebViewとVolleyで使いまわすとき

参考URL: http://stackoverflow.com/questions/16819245/what-is-the-simplest-way-to-load-an-image-using-volley-when-i-need-to-use-a-cook

そもそもログインをVolleyでやってそのCookieをWebViewで共有すればいいのであまり需要ないかも

   private void login()

    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpGet httpGet = new HttpGet(encodeURL);
    HttpResponse objResponse = httpClient.execute(httpGet);
    if (objResponse.getStatusLine().getStatusCode() < 400){  
        InputStream objStream = objResponse.getEntity().getContent();  
        InputStreamReader objReader = new InputStreamReader(objStream);  
        BufferedReader objBuf = new BufferedReader(objReader);  
        StringBuilder objJson = new StringBuilder();  
        String sLine;  
        while((sLine = objBuf.readLine()) != null){  
            objJson.append(sLine);  
        }  
        response = objJson.toString();  
        objStream.close();  
    }

    CookieStore cookieStr = httpClient.getCookieStore();
    cookieStr.clearExpired(new java.util.Date());
    List<Cookie> cookies = cookieStr.getCookies();
    CookieManager cookieManager = CookieManager.getInstance();
    for (Cookie cookie : cookies) {
        String cookieString = cookie.getName() + "=" + cookie.getValue();

        // WebViewにcookieを共有
        cookieManager.setCookie("http://hogehoge.com", cookieString);
        CookieSyncManager.getInstance().sync();
        
        // Volleyにcoolieを共有
        CustomHurlStack customHurlStack = new CustomHurlStack(cookieString);
        mQueue = Volley.newRequestQueue(MainActivity.this, customHurlStack);
    }

    mWebView.loadUrl(loginAfterPageUrl);
    mWebView.setWebViewClient(new WebViewClient() {
        @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
            }
            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
            }
    }
    mWebView.setWebChromeClient(new WebChromeClient());
}

public class CustomHurlStack extends HurlStack {

    public String cookie;
    
    public CustomHurlStack(String cookie) {
            super();
            this.cookie = cookie;
    }

    @Override
    protected HttpURLConnection createConnection(URL url) throws IOException {
        // Create a connection with custom attributes
        HttpURLConnection conn = super.createConnection(url);
        conn.addRequestProperty("User-Agent", "myUserAgent/1.0");
        conn.addRequestProperty("cookie", this.cookie);
        return conn; 
    }
}