且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Android应用程序仍然登录到网站,饼干?会议?

更新时间:2023-10-18 08:32:16

一般情况下,在Java中的HttpURLConnection可以设置/得到一个cookie这种方式(这里是整个连接过程)。下面的code是在我ConnectingThread的run(),使所有连接的活动类继承。它发送的所有请求都有着共同的静态sCookie字符串。因此,你可以保持一个共同的国家一样被记录开/关:

Generally, in Java HttpURLConnection you can set / get a cookie this way (here is the whole connection process). The code below is in my ConnectingThread's run(), from which all the connecting activity classes inherit. All share common static sCookie string which is sent with all the requests. Therefore you can maintain a common state like being logged on / off:

        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();