2

我希望用户能够单击链接,然后在后端,我需要能够自动登录用户,以便他们根本看不到登录屏幕。在我发出发布请求后,我能够从我尝试登录的站点成功获取登录 cookie,但是当我查看重定向到站点主页的 HTTP 请求时,看起来 cookie 没有得到根据我在 Firebug 中看到的内容发送。如何成功添加 cookie 并将其发送到我尝试登录的服务器?

        DefaultHttpClient httpclient = new DefaultHttpClient();
        HttpPost httpost = new HttpPost("https://mycompany.atlassian.net/wiki/dologin.action");

        CookieHandler.setDefault(new CookieManager());

        List <NameValuePair> nvps = new ArrayList <NameValuePair>();
        nvps.add(new BasicNameValuePair("os_username", "user"));
        nvps.add(new BasicNameValuePair("os_password", "pass"));
        nvps.add(new BasicNameValuePair("login", "Log In"));

        httpost.setHeader("Accept","*/*");
        httpost.setHeader("Content-Type", "application/x-www-form-urlencoded");
        httpost.getParams().setParameter(
                ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY);

        httpost.setEntity(new UrlEncodedFormEntity(nvps, Consts.UTF_8));

        HttpResponse response = null;
        try {
            response = httpclient.execute(httpost);
            HttpEntity entity = response.getEntity();
            EntityUtils.consume(entity);
            System.out.println("Login form get: " + response.getStatusLine());
        } catch (ClientProtocolException e1) {
            e1.printStackTrace();
        } catch (IOException e1) {
            e1.printStackTrace();
        }  

        httpclient.getConnectionManager().shutdown();

        System.out.println("Post logon cookies:");
        List<Cookie> cookies = httpclient.getCookieStore().getCookies();
        ExternalContext ec = FacesContext.getCurrentInstance().getExternalContext();
        HttpServletResponse servletResponse = (HttpServletResponse) ec.getResponse();

        if (cookies.isEmpty()) {
            System.out.println("None");
        } else {
            for (int i = 0; i < cookies.size(); i++) {
                javax.servlet.http.Cookie cookie = new javax.servlet.http.Cookie(cookies.get(i).getName(), cookies.get(i).getValue());
                cookie.setDomain(cookies.get(i).getDomain());
                cookie.setPath(cookies.get(i).getPath());
                cookie.setMaxAge(10000);
                cookie.setSecure(true);
                servletResponse.addCookie(cookie);
            }
        }
        try {
            servletResponse.sendRedirect("https://mycompany.atlassian.net");
        }
        catch (IOException e) {
        }
4

0 回答 0