How do I add basic authentication for the default client of the httpClient library? I have seen examples where they use client.getCredentialProvider()
, however I think all of this methods are for library version 4.0.1 or 3.x. Is there a new example of how to do this? Thanks a lot.
如何为httpClient库的默认客户端添加基本身份验证?我见过他们使用client.getCredentialProvider()的例子,但我认为所有这些方法都适用于库版本4.0.1或3.x.有没有一个如何做到这一点的新例子?非常感谢。
6 个解决方案
#1
-1
We do basic authentication with HttpClient
, but we do not use CredentialProvider
. Here's the code:
我们使用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);
UPDATE: A stated in the comments, the HttpClient.getState()
methos is available in version 3.x of the API. However, newer versions of the API doesn't support that method.
更新:在注释中声明,HttpClient.getState()方法在API的3.x版中可用。但是,较新版本的API不支持该方法。
#2
70
CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY,
new UsernamePasswordCredentials("username", "password"));
CloseableHttpClient httpClient =
HttpClientBuilder.create().setDefaultCredentialsProvider(credentialsProvider).build();
#3
19
Didn't you download the example from the website?And examples are here: httpcomponents-client-4.1.3\examples\org\apache\http\examples\client
你没有从网站上下载这个例子吗?这里的例子如下:httpcomponents-client-4.1.3 \ examples \ org \ apache \ http \ examples \ client
As for https,Just see ClientAuthentication.java:
至于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();
}
}
}
So in short :
简而言之:
DefaultHttpClient httpclient = new DefaultHttpClient();
httpclient.getCredentialsProvider().setCredentials(
new AuthScope("localhost", 443),
new UsernamePasswordCredentials("username", "password"));
#4
8
Another modern option for 4.3 is to use the Fluent extension:
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();
#5
4
DefaultHttpClient has getCredentialsProvider() but HttpClient doesn't. You need to declare DefaultHttpClient client = ... instead of HttpClient client = ...
DefaultHttpClient具有getCredentialsProvider()但HttpClient没有。你需要声明DefaultHttpClient client = ...而不是HttpClient client = ...
#6
0
I had this requirement of invoking a URL with Basic Authentication which also required proxy settings. This is what worked for me.
我有这个要求使用基本身份验证调用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();
}
}
}
#1
-1
We do basic authentication with HttpClient
, but we do not use CredentialProvider
. Here's the code:
我们使用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);
UPDATE: A stated in the comments, the HttpClient.getState()
methos is available in version 3.x of the API. However, newer versions of the API doesn't support that method.
更新:在注释中声明,HttpClient.getState()方法在API的3.x版中可用。但是,较新版本的API不支持该方法。
#2
70
CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY,
new UsernamePasswordCredentials("username", "password"));
CloseableHttpClient httpClient =
HttpClientBuilder.create().setDefaultCredentialsProvider(credentialsProvider).build();
#3
19
Didn't you download the example from the website?And examples are here: httpcomponents-client-4.1.3\examples\org\apache\http\examples\client
你没有从网站上下载这个例子吗?这里的例子如下:httpcomponents-client-4.1.3 \ examples \ org \ apache \ http \ examples \ client
As for https,Just see ClientAuthentication.java:
至于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();
}
}
}
So in short :
简而言之:
DefaultHttpClient httpclient = new DefaultHttpClient();
httpclient.getCredentialsProvider().setCredentials(
new AuthScope("localhost", 443),
new UsernamePasswordCredentials("username", "password"));
#4
8
Another modern option for 4.3 is to use the Fluent extension:
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();
#5
4
DefaultHttpClient has getCredentialsProvider() but HttpClient doesn't. You need to declare DefaultHttpClient client = ... instead of HttpClient client = ...
DefaultHttpClient具有getCredentialsProvider()但HttpClient没有。你需要声明DefaultHttpClient client = ...而不是HttpClient client = ...
#6
0
I had this requirement of invoking a URL with Basic Authentication which also required proxy settings. This is what worked for me.
我有这个要求使用基本身份验证调用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();
}
}
}