Android: log into website and preserve session/cookie using DefaultHttpClient

前端 未结 4 1685
死守一世寂寞
死守一世寂寞 2021-02-08 11:08

I\'ve been through different tutorials and this website, but couldn\'t find a proper solution. On the other hand, I\'ve seen apps logging into websites and requesting further in

4条回答
  •  悲&欢浪女
    2021-02-08 11:46

    In an application that I have to login to. First i have to run a GET followed by a POST and then the GET again. The First get will instantiate a Jsession Id for my connection. The POST will authenticate my ID and then the original get GET will return the real content.

    The code below is for an app running in JBoss

    public boolean login() {
        HttpGet  httpGet = new HttpGet(  "http://localhost:8080/gwt-console-server/rs/identity/secure/sid/");
        HttpPost httpPost = new HttpPost("http://localhost:8080/gwt-console-server/rs/identity/secure/j_security_check");
        HttpResponse response = null;
    
        List nvps = new ArrayList();
        nvps.add(new BasicNameValuePair(USER_FIELD, userName));
        nvps.add(new BasicNameValuePair(PASS_FIELD, password));
    
        try {
            httpPost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
    
            response = httpClient.execute(httpGet);
            EntityUtils.consume(response.getEntity());
    
            response = httpClient.execute(httpPost);
            EntityUtils.consume(response.getEntity());
    
            response = httpClient.execute(httpGet);
            String sessionId =EntityUtils.toString(response.getEntity());
    
            String cookieId =""; 
            List cookies = ((AbstractHttpClient) httpClient).getCookieStore().getCookies();
            for (Cookie cookie: cookies){
                if (cookie.getName().equals("JSESSIONID")){
                    cookieId = cookie.getValue();
                }
            }
    
            if(sessionId!= null && sessionId.equals(cookieId) ){
                return true;
            }
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return false;   
    }
    

提交回复
热议问题