简体   繁体   English

不使用CookieManager的Android会话cookie

[英]Android Session cookies without using CookieManager

My application makes multiple web calls in order to get authentication. 我的应用程序进行了多个Web调用以获取身份验证。 I need to store this session in a cookie. 我需要将此会话存储在cookie中。 I wanted to use Cookie Manager but after doing some research, I found out it is only available to API 9 and above and my application needs to be backward compatible. 我想使用Cookie Manager,但经过一些研究,发现它仅适用于API 9及更高版本,并且我的应用程序需要向后兼容。

I make my web connections using HTTPURLConnection to a secure HTTPS. 我使用HTTPURLConnection建立到安全HTTPS的Web连接。 Quick example of my code 我的代码的简单示例

    public String iStream_to_String(InputStream is)
{
    BufferedReader rd = new BufferedReader(new InputStreamReader(is), 4096);
    String line;
    StringBuilder sb = new StringBuilder();
    try
    {
        while ((line = rd.readLine()) != null)
        {
            sb.append(line);
        }
        rd.close();

    } catch (IOException e)
    {
        e.printStackTrace();
    }
    String contentOfMyInputStream = sb.toString();
    return contentOfMyInputStream;
}

final static HostnameVerifier DO_NOT_VERIFY = new HostnameVerifier()
{
    public boolean verify(String hostname, SSLSession session)
    {
        return true;
    }
};

/**
 * Trust every server - dont check for any certificate
 */
private static void trustAllHosts()
{
    // Create a trust manager that does not validate certificate chains
    TrustManager[] trustAllCerts = new TrustManager[]
    { new X509TrustManager()
    {
        public java.security.cert.X509Certificate[] getAcceptedIssuers()
        {
            return new java.security.cert.X509Certificate[]
            {};
        }

        public void checkClientTrusted(X509Certificate[] chain,
                String authType) throws CertificateException
        {
        }

        public void checkServerTrusted(X509Certificate[] chain,
                String authType) throws CertificateException
        {
        }
    } };

    // Install the all-trusting trust manager
    try
    {
        SSLContext sc = SSLContext.getInstance("TLS");
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        HttpsURLConnection
                .setDefaultSSLSocketFactory(sc.getSocketFactory());
    } catch (Exception e)
    {
        e.printStackTrace();
    }
}

Then I make a request like so 然后我发出这样的请求

    try
    {
        url = new URL(url1);



        trustAllHosts();
           HttpsURLConnection https = (HttpsURLConnection) url.openConnection();
       https.setHostnameVerifier(DO_NOT_VERIFY);
        http = https;

        InputStream in = new BufferedInputStream(http.getInputStream());

        sAuthenticateP1 = iStream_to_String(in);
        in.close();


    } catch (Exception e)
    {
        e.printStackTrace();
    }

The full authentication is done in 4 steps. 完整身份验证通过4个步骤完成。 I need to have it so the session is remembered throughout the 4 steps. 我需要使用它,以便在整个4个步骤中记住该会话。 Seeing I can't use CookieManager, I have been looking around for other ways of doing this, but can't seem to find any. 看到我无法使用CookieManager,我一直在寻找实现此目的的其他方法,但似乎找不到任何方法。 Would anyone be able to point me in the right direction. 任何人都可以指出正确的方向。

Thanks in advance!! 提前致谢!!

Figured it out. 弄清楚了。 Incase anyone else is having similar problem, will give quick outline of code. 如果其他任何人有类似的问题,将快速给出代码轮廓。 As I said before mine is a several step authentication process. 正如我之前所说的那样,认证过程需要几步。 So after the first request, after you have received a response, take the cookie like so 因此,在收到第一个请求后,您将收到一个响应,然后像这样获取Cookie

String cookie = http.getRequestProperty("Cookie");
            if (cookie != null && cookie.length() > 0)
            {
                sCookie = cookie;
                Log.v("cookie2", sCookie);
            }

sCookie is a static string variable I have set up. sCookie是我设置的静态字符串变量。 Then in the next request, after this line 然后在下一个请求中,在此行之后

https = (HttpsURLConnection) url.openConnection(); 

Just put 刚放

            https.setRequestProperty("Cookie", sCookie);
            https.setRequestMethod("POST");
            https.setDoInput(true);
            https.setDoOutput(true);

And do the same thing for each request after that requires the session, and it should work fine 在需要会话之后,对每个请求执行相同的操作,它应该可以正常工作

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM