区分HTTPOnly cookie来自android中的其他cookie

时间:2014-07-04 09:36:49

标签: java android cookies httponly

在我目前的项目中,我们正在实现Android应用程序和服务器之间的会话处理。 现在我们的设计Android应用程序应该只接受HTTP Cookie并删除所有其他cookie。 但是看看所有可用的选项,我找不到任何可以帮助我识别cookie是否为HTTPOnly的类或方法。

我以下列方式存储Cookie:

        connections = (HttpURLConnection) serverURL.openConnection();
        // Setting cookies manager
        java.net.CookieManager manager = new java.net.CookieManager();
        manager.setCookiePolicy(new CookiePolicy() {

            @Override
            public boolean shouldAccept(URI uri, HttpCookie cookie) {
                return cookie.getSecure();
            }
        });
        CookieHandler.setDefault(manager);

        connections.setDoInput(true);
        connections.setDoOutput(true);
        connections.setConnectTimeout(TIME_OUT);

        connections.getOutputStream().write(data);

        InputStream inputStream = connections.getInputStream();
        CookieStore cookieJar = manager.getCookieStore();
        if (cookieJar != null) {
            List<HttpCookie> cookies = cookieJar.getCookies();
            for (HttpCookie httpCookie : cookies) {

                Log.i("yash", httpCookie.toString());
            }
        }

但是这个HttpCookie没有任何HTTPOnly方法。

通过一些谷歌浏览,我发现RFC 6265具有HTTPOnly属性,它也阻碍了RFC 2965.但为什么谷歌不支持这个RFC 6265?

1 个答案:

答案 0 :(得分:1)

根据the class documentation支持HttpOnly但由于某种原因,该字段没有任何访问者或增变器。

为了能够访问和修改httpOnly字段,您应该使用反射:

// Workaround httpOnly (getter)
private boolean getHttpOnly() {
    try {
        Field fieldHttpOnly = cookie.getClass().getDeclaredField("httpOnly");
        fieldHttpOnly.setAccessible(true);

        return (boolean) fieldHttpOnly.get(cookie);
    } catch (Exception e) {
        // NoSuchFieldException || IllegalAccessException ||
        // IllegalArgumentException
        Log.w(TAG, e);
    }
    return false;
}

// Workaround httpOnly (setter)
private void setHttpOnly(boolean httpOnly) {
    try {
        Field fieldHttpOnly = cookie.getClass().getDeclaredField("httpOnly");
        fieldHttpOnly.setAccessible(true);

        fieldHttpOnly.set(cookie, httpOnly);
    } catch (Exception e) {
        // NoSuchFieldException || IllegalAccessException ||
        // IllegalArgumentException
        Log.w(TAG, e);
    }
}