⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 httpclient.java

📁 这是linux下ssl vpn的实现程序
💻 JAVA
📖 第 1 页 / 共 2 页
字号:

        if (preemptiveAuthentication && credentials != null) {
            // Discard old authenticator and create a new one
            BasicAuthentication authenticator = new BasicAuthentication(method.getURI());
            authenticator.setCredentials(credentials);
            authenticator.setConnection(con);
            authenticator.setChallenge("Basic");
            authenticator.setAuthenicationHeader(method.getName().equals("CONNECT") ? "proxy-authenticate" : "www-authenticate");
            authenticator.setAuthorizationHeader(method.getName().equals("CONNECT") ? "proxy-authorization" : "authorization");
            con.setAuthenticator(authenticator);
        }

        connections.checkConnection(con);

        if (includeCookies) {
            String cookiesHeader = "";
            for (Enumeration e = cookies.elements(); e.hasMoreElements();) {
                Cookie cookie = (Cookie) e.nextElement();

                // Evaluate whether the cookie should be included
                Date now = new Date();
                if (cookie.getExpires() == null || cookie.expires.after(now)) {
                    if (method.getURI().startsWith(cookie.getPath()) && getHost().endsWith(cookie.getDomain())
                                    && (cookie.isSecure() == isSecure || !cookie.isSecure())) {
                        cookiesHeader += cookie + "; ";
                    }
                }
            }

            if (!cookiesHeader.equals("")) {
                request.setHeaderField("Cookie", cookiesHeader);
            }
        }

        if (con.isKeepAlive())
            request.setHeaderField("Connection", "Keep-Alive");

        if (con.getAuthenticator() != null && con.getAuthenticator().canAuthenticate()) {
            /* DEBUG */log.debug("Setting authentication credentials for " + con.getAuthenticator().getScheme());
            try {
                request.removeFields(con.getAuthenticator().getAuthorizationHeader());
                con.getAuthenticator().authenticate(request, method);
            } catch (Exception ex) {
                /* DEBUG */log.info("Got exception from HTTP authenticator instance", ex);
                con.setAuthenticator(null);
            }
        }

    }

    HttpResponse execute(HttpRequest request, HttpMethod method, HttpConnection con) throws IOException, HttpException,
                    UnsupportedAuthenticationException, AuthenticationCancelledException {

        prepareRequest(request, method, con);

        /* DEBUG */log.info("Executing method " + method.getName() +
        /* DEBUG */" on connection " + con.getHost());

        return processResponse(request, method, con, method.execute(request, con));
    }

    HttpConnection executeAsync(HttpRequest request, AsyncHttpMethod method, HttpConnection con) throws IOException, HttpException,
                    UnsupportedAuthenticationException, AuthenticationCancelledException {

        prepareRequest(request, method, con);

        /* DEBUG */log.debug("Executing method " + method.getName() +
        /* DEBUG */" on connection " + con.getHost());

        method.executeAsync(request, con);

        return con;
    }
    
    synchronized HttpResponse processResponse(HttpRequest request, HttpMethod method, HttpConnection con, HttpResponse response)
                    throws IOException, HttpException, UnsupportedAuthenticationException, AuthenticationCancelledException {

        // Process any cookies
        if (includeCookies) {
            String[] cookies = response.getHeaderFields("Set-Cookie");
            if (cookies != null) {
                for (int i = 0; i < cookies.length; i++) {
                    this.cookies.addElement(new Cookie(cookies[i]));
                }
            }
        }

        try {
            /**
             * Now process the response to see if we need to handle
             * authentication
             */
            switch (response.getStatus()) {
                case 401:
                case 407:
                    if (con.getAuthenticator() != null) {
                        int success = con.getAuthenticator().processResponse(response);

                        switch (success) {
                            case HttpAuthenticator.AUTHENTICATION_COMPLETED:
                                // w00t we're in
                                return response;
                            case HttpAuthenticator.AUTHENTICATION_FAILED:
                                // Up the number of cycles and try again
                                request.cycles++;
                                credentialsFailed = true;
                                break;
                            case HttpAuthenticator.AUTHENTICATION_IN_PROGRESS:
                            default:
                        // Do nothing just keep on authenticating
                        }

                    } else if (credentials == null && prompt == null) {
                        return response;
                    }

                    if (con.getAuthenticator() == null || request.cycles < maxAuthenticationAttempts)
                        return doAuthentication(response.getStatus() == 401 ? "www-authenticate" : "proxy-authenticate", response
                                        .getStatus() == 401 ? "authorization" : "proxy-authorization", request, method, response,
                                        con);
                    else
                        return response;
                default:
                    // Set the authenticator as complete and return
                    if (con.getAuthenticator() != null) {
                        credentials = con.getAuthenticator().credentials;
                        con.getAuthenticator().complete();
                    }
                    return response;

            }
        } catch (UnsupportedAuthenticationException ex) {
            /**
             * We dont support this type of authentication so return the
             * response
             */
            return response;
        }
    }

    private HttpResponse doAuthentication(String authenticateHeader, String authorizationHeader, HttpRequest request,
                    HttpMethod method, HttpResponse response, HttpConnection con) throws IOException, HttpException,
                    UnsupportedAuthenticationException, AuthenticationCancelledException {

        // Check for failed authentication limit
        if(credentialsFailed) {
            con.setAuthenticator(null);
            return response;
        }
        // If we're called we are disgaurding the previous response
        response.close(false);

        // Authorization required
        String[] challenges = response.getHeaderFields(authenticateHeader);

        if (challenges == null)
            return response;

        /* DEBUG */for (int i = 0; i < challenges.length; i++) {
        /* DEBUG */log.info(con.getHost() + " requires " +
        /* DEBUG */HttpAuthenticatorFactory.getAuthenticationMethod(challenges[i]) +
        /* DEBUG */" authentication");
        /* DEBUG */}

        /**
         * If we don't already have an authenticator we should create one
         */
        if (credentials == null && prompt == null && con.getAuthenticator() == null) {
            // We cannot authenticate as we do not have any credentials
            // or a prompt
            return response;
        }

        /**
         * If we got this far then we can authenticate so try to create an
         * appropriate authenticator
         */
        if (con.getAuthenticator() == null || !con.getAuthenticator().getURI().startsWith(method.getURI())) {
            con.setAuthenticator(HttpAuthenticatorFactory.createAuthenticator(con, challenges, authenticateHeader,
                            authorizationHeader, preferedAuthentication, method.getURI()));
        }

        if (credentials != null) {
            /* DEBUG */log.info("Setting user credentials");
            con.getAuthenticator().setCredentials(credentials);
        } else if (prompt != null && con.getAuthenticator().wantsPrompt()) {
            /* DEBUG */log.info("Prompting user for credentials");
            if (!prompt.promptForCredentials(con.getAuthenticator())) {
                throw new AuthenticationCancelledException();
            }
        }

        return execute(request, method, con);
    }
    
    public HttpResponse execute(HttpMethod method) throws UnknownHostException, IOException, HttpException,
                    UnsupportedAuthenticationException, AuthenticationCancelledException {
        /* DEBUG */log.debug("Executing " + method.getName());
        for (int i = 0; i < 2; i++) {
            try {
                return execute(new HttpRequest(), method, connections.getConnection());
            } catch (EOFException eof) {
                /* DEBUG */log.warn("EOFException. " + (i == 0 ? "Attempting again." : "Giving up."));
            }
        }
        throw new EOFException("Could not connect after two attempts.");
    }

    public HttpConnection executeAsync(AsyncHttpMethod method) throws UnknownHostException, IOException, HttpException,
                    UnsupportedAuthenticationException, AuthenticationCancelledException {
        /* DEBUG */log.debug("Executing " + method.getName());
        return executeAsync(new HttpRequest(), method, connections.getConnection());
    }

    public void setIncludeCookies(boolean includeCookies) {
        this.includeCookies = includeCookies;
    }

    public void setPreemtiveAuthentication(boolean preemptiveAuthentication) {
        this.preemptiveAuthentication = preemptiveAuthentication;
    }
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -