【问题标题】:Logging out programmatically after providing credentials using HttpClient [duplicate]使用 HttpClient 提供凭据后以编程方式注销 [重复]
【发布时间】:2014-06-17 04:56:11
【问题描述】:

我正在使用 Java 中的 Apache HttpClient 4.3.4 库以编程方式向需要身份验证的 URL 提供凭据。这就是我的代码中的内容:

public static void clientAuthentication() throws Exception {
    CredentialsProvider credsProvider = new BasicCredentialsProvider();

    credsProvider.setCredentials(
            AuthScope.ANY,
            new UsernamePasswordCredentials("username", "password"));

    CloseableHttpClient httpclient = HttpClients.custom()
            .setDefaultCredentialsProvider(credsProvider)
            .build();

    try {
        HttpGet httpget = new HttpGet("http://www.example.com");

        System.out.println("Executing request " + httpget.getRequestLine());
        CloseableHttpResponse response = httpclient.execute(httpget);

        try {
            System.out.println("----------------------------------------");
            System.out.println(response.getStatusLine());
            for (Header h : response.getAllHeaders()){
                System.out.println(h.toString());
            }

            EntityUtils.consume(response.getEntity());
        } finally {
            response.close();
        }
    } finally {
        httpclient.close();
    }
}

我能够成功通过 URL 进行身份验证,因为我收到了 200 状态代码。我的问题是,既然我已经以编程方式“登录”了,有没有办法以编程方式“注销”?此 URL 没有任何“注销”按钮或类似的东西;所以我想知道如何以编程方式注销。

谢谢。

【问题讨论】:

    标签: java http authentication httpclient apache-httpclient-4.x


    【解决方案1】:

    注销我不这么认为。你可以在httpclient中使用超时方法。

    HttpConnectionParams.setConnectionTimeout(httpParams, 30 *  1000);
    

    【讨论】:

      【解决方案2】:

      应该有一个用于注销的 API 端点。你需要调用它。

      【讨论】:

        【解决方案3】:

        我认为 HTTPS BASIC 没有注销会话的机制。 (我假设您的服务器使用 BASIC 身份验证)。

        rfc 表示会话在收到下一个身份验证质询之前有效。因此,一种丑陋的方法是使用不正确的凭据进行另一次身份验证尝试。但在您这样做之前请三思,因为太多不正确的身份验证尝试可能会让人们认为您在暴力破解密码。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2012-01-10
          • 2012-06-15
          • 2019-05-06
          • 1970-01-01
          • 2011-03-07
          • 1970-01-01
          • 2015-06-19
          • 2015-07-22
          相关资源
          最近更新 更多