web-dev-qa-db-ja.com

Apache HttpClient(4.1以降):基本認証を行う方法

HttpClientライブラリのデフォルトクライアントに基本認証を追加するにはどうすればよいですか? client.getCredentialProvider()を使用する例を見てきましたが、このメソッドはすべてライブラリバージョン4.0.1または3.x向けであると思います。これを行う方法の新しい例はありますか?どうもありがとう。

38
Pablo
CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY, 
    new UsernamePasswordCredentials("username", "password"));
CloseableHttpClient httpClient = 
    HttpClientBuilder.create().setDefaultCredentialsProvider(credentialsProvider).build();
77
Joe

Webサイトからサンプルをダウンロードしませんでしたか?また、サンプルは次のとおりです: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 httpclient = new DefaultHttpClient();
httpclient.getCredentialsProvider().setCredentials(
                    new AuthScope("localhost", 443),
                    new UsernamePasswordCredentials("username", "password"));
20
Jacob

4.3のもう1つの最新オプションは、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();
9
Barett

DefaultHttpClientにはgetCredentialsProvider()がありますが、HttpClientにはありません。 HttpClient client = ...の代わりにDefaultHttpClient client = ...を宣言する必要があります。

4
stefan

プロキシ設定も必要とする基本認証で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();
    }
}





}
0
Amit Singh