Android应用仍保持登录网站,Cookie?会议?

时间:2010-06-25 03:28:10

标签: android authentication session cookies

我正在寻找一个基本上是基于文本的游戏网站的自定义视图的Android应用程序。我知道如何做HttpPosting等,所以发送登录信息相对简单。但我的问题是,我将如何进行导航网站?我从来没有真正使用客户端的会话和cookie。 Cookie是实现此目的的正确方法吗?如何在访问后续页面时将信息传递回服务器?

我希望这是有道理的

1 个答案:

答案 0 :(得分:3)

通常,在Java HttpURLConnection中,您可以通过这种方式设置/获取cookie(这是整个连接过程)。下面的代码在我的ConnectingThread的run()中,所有连接活动类都从该run_()继承。 All共享与所有请求一起发送的公共静态sCookie字符串。因此,您可以保持常见状态,例如登录/注销:

        HttpURLConnection conn = (HttpURLConnection) url.openConnection();             

        //set cookie. sCookie is my static cookie string
        if(sCookie!=null && sCookie.length()>0){
            conn.setRequestProperty("Cookie", sCookie);                  
        }

        // Send data
        OutputStream os = conn.getOutputStream(); 
        os.write(mData.getBytes());
        os.flush();
        os.close(); 

        // Get the response!
        int httpResponseCode = conn.getResponseCode();         
        if (httpResponseCode != HttpURLConnection.HTTP_OK){
           throw new Exception("HTTP response code: "+httpResponseCode); 
        }

        // Get the data and pass them to the XML parser
        InputStream inputStream = conn.getInputStream();                
        Xml.parse(inputStream, Xml.Encoding.UTF_8, mSaxHandler);                
        inputStream.close();

        //Get the cookie
        String cookie = conn.getHeaderField("set-cookie");
        if(cookie!=null && cookie.length()>0){
            sCookie = cookie;              
        }

        /*   many cookies handling:                  
        String responseHeaderName = null;
        for (int i=1; (responseHeaderName = conn.getHeaderFieldKey(i))!=null; i++) {
            if (responseHeaderName.equals("Set-Cookie")) {                  
            String cookie = conn.getHeaderField(i);   
            }
        }*/                

        conn.disconnect();                
相关问题