Apache HttpClient(4.1及更新版):如何进行基本身份验证?

Pab*_*blo 40 java apache-httpcomponents apache-httpclient-4.x

如何为httpClient库的默认客户端添加基本身份验证?我已经看到了他们使用的示例client.getCredentialProvider(),但我认为所有这些方法都适用于库版本4.0.1或3.x. 有没有一个如何做到这一点的新例子?非常感谢.

Joe*_*Joe 79

CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY, 
    new UsernamePasswordCredentials("username", "password"));
CloseableHttpClient httpClient = 
    HttpClientBuilder.create().setDefaultCredentialsProvider(credentialsProvider).build();
Run Code Online (Sandbox Code Playgroud)

  • 这是v4.3的最佳答案.请注意,它会抢先将凭据发送到*all*URL. (6认同)
  • 要解决artbristol的问题,请更改AuthScope. (5认同)

Jac*_*cob 20

你没有从网站上下载这个例子吗?这里有例子:httpcomponents-client-4.1.3\examples\org\apache\_hys\examples\client

至于https,请参阅ClientAuthentication.java:

/*
 * ====================================================================
 *
 *  Licensed to the Apache Software Foundation (ASF) under one or more
 *  contributor license agreements.  See the NOTICE file distributed with
 *  this work for additional information regarding copyright ownership.
 *  The ASF licenses this file to You under the Apache License, Version 2.0
 *  (the "License"); you may not use this file except in compliance with
 *  the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */

package org.apache.http.examples.client;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

/**
 * A simple example that uses HttpClient to execute an HTTP request against
 * a target site that requires user authentication.
 */
public class ClientAuthentication {

    public static void main(String[] args) throws Exception {
        DefaultHttpClient httpclient = new DefaultHttpClient();
        try {
            httpclient.getCredentialsProvider().setCredentials(
                    new AuthScope("localhost", 443),
                    new UsernamePasswordCredentials("username", "password"));

            HttpGet httpget = new HttpGet("https://localhost/protected");

            System.out.println("executing request" + httpget.getRequestLine());
            HttpResponse response = httpclient.execute(httpget);
            HttpEntity entity = response.getEntity();

            System.out.println("----------------------------------------");
            System.out.println(response.getStatusLine());
            if (entity != null) {
                System.out.println("Response content length: " + entity.getContentLength());
            }
            EntityUtils.consume(entity);
        } finally {
            // When HttpClient instance is no longer needed,
            // shut down the connection manager to ensure
            // immediate deallocation of all system resources
            httpclient.getConnectionManager().shutdown();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

简而言之:

DefaultHttpClient httpclient = new DefaultHttpClient();
httpclient.getCredentialsProvider().setCredentials(
                    new AuthScope("localhost", 443),
                    new UsernamePasswordCredentials("username", "password"));
Run Code Online (Sandbox Code Playgroud)

  • DefaultHttpClient在4.x中已弃用.您可以使用https://hc.apache.org/httpcomponents中的示例https://hc.apache.org/httpcomponents-client-ga/httpclient/examples/org/apache/http/examples/client/ClientAuthentication.java -client-ga/examples.html. (8认同)

Bar*_*ett 10

4.3的另一个现代选项是使用Fluent扩展:

Executor executor = Executor.newInstance()
        .auth(new HttpHost("somehost"), "username", "password")
        .auth(new HttpHost("securehost", 443, "https"), "username", "password") // https example
        .auth(new HttpHost("myproxy", 8080), "username", "password")
        .authPreemptive(new HttpHost("myproxy", 8080));

String content = executor.execute(Request.Get("http://somehost/"))
        .returnContent().asString();
Run Code Online (Sandbox Code Playgroud)

  • 为了使这项工作在https连接上有所作为,我们不需要忘记在HttpHost上添加端口和方案(新的HttpHost("somehost",443,"https"),因为默认端口和方案是80,http. (3认同)

Car*_*ron -2

我们使用 进行基本身份验证HttpClient,但我们不使用CredentialProvider。这是代码:

HttpClient client = factory.getHttpClient(); //or any method to get a client instance
Credentials credentials = new UsernamePasswordCredentials(username, password);
client.getState().setCredentials(AuthScope.ANY, credentials);
Run Code Online (Sandbox Code Playgroud)

更新: 评论中指出,该方法在API 3.x 版本HttpClient.getState()中可用。但是,较新版本的 API不支持该方法。

  • 这很好,但是 4.x 代码中不存在 HttpClient.getState()。这仅适用于 3.1 及更早版本。 (33认同)
  • 我是唯一一个对为什么这是公认答案感到困惑的人吗? (12认同)