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

Java ApacheHttpClient(4.1及更新版本):如何进行基本身份验证?,java,apache-httpclient-4.x,apache-httpcomponents,Java,Apache Httpclient 4.x,Apache Httpcomponents,如何为httpClient库的默认客户端添加基本身份验证?我看到过使用client.getCredentialProvider()的示例,但是我认为所有这些方法都适用于库版本4.0.1或3.x。有没有一个新的例子来说明如何做到这一点?非常感谢。我们使用HttpClient进行基本身份验证,但不使用CredentialProvider。代码如下: HttpClient client = factory.getHttpClient(); //or any method to get a client

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

我们使用
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);
更新:
注释中指出,
HttpClient.getState()
方法在中可用。但是,不支持该方法。

您不是从网站下载了示例吗?示例如下:httpcomponents-client-4.1.3\examples\org\apache\http\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();
        }
    }
}

DefaultHttpClient具有getCredentialsProvider(),但HttpClient没有。 你需要申报 DefaultHttpClient客户端=。。。 而不是
HttpClient=…

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

CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY, 
    new UsernamePasswordCredentials("username", "password"));
CloseableHttpClient httpClient = 
    HttpClientBuilder.create().setDefaultCredentialsProvider(credentialsProvider).build();
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();

我需要使用基本身份验证调用URL,这也需要代理设置。 这就是我的工作

    import java.io.IOException;
    import java.io.InputStream;
    import java.io.StringReader;
    import java.util.HashMap;
    import java.util.Map;

    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.parsers.ParserConfigurationException;

    import org.apache.commons.httpclient.Credentials;
    import org.apache.commons.httpclient.HostConfiguration;
    import org.apache.commons.httpclient.HttpClient;
    import org.apache.commons.httpclient.HttpMethod;
    import org.apache.commons.httpclient.HttpStatus;
    import org.apache.commons.httpclient.UsernamePasswordCredentials;
    import org.apache.commons.httpclient.auth.AuthScope;
    import org.apache.commons.httpclient.methods.GetMethod;
    import org.w3c.dom.*;

    import javax.xml.parsers.*;


    import org.xml.sax.InputSource;
    import org.xml.sax.SAXException;

    public class TestResponse {

    public final static String TESTURL="https://myURL";
    private static final String PROXY_HOST = "www2.proxyXYS";
    private static final int PROXY_PORT = 8080;


    public static void main (String args[]) 
    {
    HttpClient client = new HttpClient();
    HttpMethod method = new GetMethod(TESTURL);
    HostConfiguration config = client.getHostConfiguration();
    config.setProxy(PROXY_HOST, PROXY_PORT);

      String username = "User";
      String password = "Pa55w0rd";


    Credentials credentials = new UsernamePasswordCredentials(username, password);
    AuthScope authScope = new AuthScope(PROXY_HOST, PROXY_PORT);

    client.getState().setProxyCredentials(authScope, credentials);
    client.getState().setCredentials(AuthScope.ANY, credentials);

    try {
        client.executeMethod(method);

        String response = method.getResponseBodyAsString();

        if (method.getStatusCode() == HttpStatus.SC_OK) {
             response = method.getResponseBodyAsString();
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        method.releaseConnection();
    }
}





}

请看这是我找到的最好的例子。。。比apache文档要好得多:这很好,但是HttpClient.getState()在4.x代码中不存在。这只适用于3.1及更早版本。我是唯一一个对为什么这是公认的答案感到困惑的人吗?这是v4.3的最佳答案。请注意,它会将凭据先发制人地发送到所有URL。要解决artbristol的问题,请更改AuthScope。@artbristol仅在您配置了先发制人身份验证时,对吗@是的,我想你是对的。这会将凭据发送到任何需要凭据的服务器,但不会发送到其他服务器。
DefaultHttpClient
现在在4.3中被弃用,尽管它只在4.0中引入!DefaultHttpClient在4.x中不推荐使用。您可以使用中的示例。DefaultHttpClient仅在4.3中被弃用。在4.1中,它并没有被弃用,因为在https连接上要想让它工作起来有点困难,所以不需要忘记在HttpHost(新的HttpHost(“somehost”,443,“https”)上添加端口和方案,因为默认端口和方案是80,http。
Executer
的完整导入路径是什么?我在
中遇到了一个错误。newInstance()
。编译器说这不存在。您使用的是哪个版本的JDK?
org.apache.http.client.fluent.Executor
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.StringReader;
    import java.util.HashMap;
    import java.util.Map;

    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.parsers.ParserConfigurationException;

    import org.apache.commons.httpclient.Credentials;
    import org.apache.commons.httpclient.HostConfiguration;
    import org.apache.commons.httpclient.HttpClient;
    import org.apache.commons.httpclient.HttpMethod;
    import org.apache.commons.httpclient.HttpStatus;
    import org.apache.commons.httpclient.UsernamePasswordCredentials;
    import org.apache.commons.httpclient.auth.AuthScope;
    import org.apache.commons.httpclient.methods.GetMethod;
    import org.w3c.dom.*;

    import javax.xml.parsers.*;


    import org.xml.sax.InputSource;
    import org.xml.sax.SAXException;

    public class TestResponse {

    public final static String TESTURL="https://myURL";
    private static final String PROXY_HOST = "www2.proxyXYS";
    private static final int PROXY_PORT = 8080;


    public static void main (String args[]) 
    {
    HttpClient client = new HttpClient();
    HttpMethod method = new GetMethod(TESTURL);
    HostConfiguration config = client.getHostConfiguration();
    config.setProxy(PROXY_HOST, PROXY_PORT);

      String username = "User";
      String password = "Pa55w0rd";


    Credentials credentials = new UsernamePasswordCredentials(username, password);
    AuthScope authScope = new AuthScope(PROXY_HOST, PROXY_PORT);

    client.getState().setProxyCredentials(authScope, credentials);
    client.getState().setCredentials(AuthScope.ANY, credentials);

    try {
        client.executeMethod(method);

        String response = method.getResponseBodyAsString();

        if (method.getStatusCode() == HttpStatus.SC_OK) {
             response = method.getResponseBodyAsString();
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        method.releaseConnection();
    }
}





}