SSLContext sslContext = SSLContext.getInstance("SSL");
// set up a TrustManager that trusts everything
sslContext.init(null, new TrustManager[] { new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
System.out.println("getAcceptedIssuers =============");
return null;
}
public void checkClientTrusted(X509Certificate[] certs,
String authType) {
System.out.println("checkClientTrusted =============");
}
public void checkServerTrusted(X509Certificate[] certs,
String authType) {
System.out.println("checkServerTrusted =============");
}
} }, new SecureRandom());
SSLSocketFactory sf = new SSLSocketFactory(sslContext);
Scheme httpsScheme = new Scheme("https", 443, sf);
SchemeRegistry schemeRegistry = new SchemeRegistry();
schemeRegistry.register(httpsScheme);
// apache HttpClient version >4.2 should use BasicClientConnectionManager
ClientConnectionManager cm = new SingleClientConnManager(schemeRegistry);
HttpClient httpClient = new DefaultHttpClient(cm);
SSLContextBuilder builder = new SSLContextBuilder();
builder.loadTrustMaterial(null, new TrustStrategy() {
@Override
public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
return true;
}
});
SSLConnectionSocketFactory sslSF = new SSLConnectionSocketFactory(builder.build(),
SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(sslSF).build();
HttpPost postRequest = new HttpPost(url);
以正常形式继续您的请求
79
这就是我做到的 -
创建我自己的MockSSLSocketFactory(下面附带的类)
用它来初始化DefaultHttpClient . 如果使用代理,则需要提供代理设置 .
初始化DefaultHTTPClient -
SchemeRegistry schemeRegistry = new SchemeRegistry();
schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));
schemeRegistry.register(new Scheme("https", 443, new MockSSLSocketFactory()));
ClientConnectionManager cm = new SingleClientConnManager(schemeRegistry);
DefaultHttpClient httpclient = new DefaultHttpClient(cm);
模拟SSL工厂 -
public class MockSSLSocketFactory extends SSLSocketFactory {
public MockSSLSocketFactory() throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException {
super(trustStrategy, hostnameVerifier);
}
private static final X509HostnameVerifier hostnameVerifier = new X509HostnameVerifier() {
@Override
public void verify(String host, SSLSocket ssl) throws IOException {
// Do nothing
}
@Override
public void verify(String host, X509Certificate cert) throws SSLException {
//Do nothing
}
@Override
public void verify(String host, String[] cns, String[] subjectAlts) throws SSLException {
//Do nothing
}
@Override
public boolean verify(String s, SSLSession sslSession) {
return true;
}
};
private static final TrustStrategy trustStrategy = new TrustStrategy() {
@Override
public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
return true;
}
};
}
如果在代理后面,需要这样做 -
HttpParams params = new BasicHttpParams();
params.setParameter(AuthPNames.PROXY_AUTH_PREF, getClientAuthPrefs());
DefaultHttpClient httpclient = new DefaultHttpClient(cm, params);
httpclient.getCredentialsProvider().setCredentials(
new AuthScope(proxyHost, proxyPort),
new UsernamePasswordCredentials(proxyUser, proxyPass));
2
使用流畅的4.5.2我必须进行以下修改才能使其正常工作 .
try {
TrustManager[] trustAllCerts = new TrustManager[] {
new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(X509Certificate[] certs, String authType) { }
public void checkServerTrusted(X509Certificate[] certs, String authType) { }
}
};
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new SecureRandom());
CloseableHttpClient httpClient = HttpClients.custom().setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE).setSslcontext(sc).build();
String output = Executor.newInstance(httpClient).execute(Request.Get("https://127.0.0.1:3000/something")
.connectTimeout(1000)
.socketTimeout(1000)).returnContent().asString();
} catch (Exception e) {
}
8
DefaultHttpClient httpclient = new DefaultHttpClient();
SSLContext sslContext;
try {
sslContext = SSLContext.getInstance("SSL");
// set up a TrustManager that trusts everything
try {
sslContext.init(null,
new TrustManager[] { new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
log.debug("getAcceptedIssuers =============");
return null;
}
public void checkClientTrusted(
X509Certificate[] certs, String authType) {
log.debug("checkClientTrusted =============");
}
public void checkServerTrusted(
X509Certificate[] certs, String authType) {
log.debug("checkServerTrusted =============");
}
} }, new SecureRandom());
} catch (KeyManagementException e) {
}
SSLSocketFactory ssf = new SSLSocketFactory(sslContext,SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
ClientConnectionManager ccm = this.httpclient.getConnectionManager();
SchemeRegistry sr = ccm.getSchemeRegistry();
sr.register(new Scheme("https", 443, ssf));
} catch (Exception e) {
log.error(e.getMessage(),e);
}
public static void main(String... args) {
try (CloseableHttpClient httpclient = createAcceptSelfSignedCertificateClient()) {
HttpGet httpget = new HttpGet("https://example.com");
System.out.println("Executing request " + httpget.getRequestLine());
httpclient.execute(httpget);
System.out.println("----------------------------------------");
} catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException | IOException e) {
throw new RuntimeException(e);
}
}
private static CloseableHttpClient createAcceptSelfSignedCertificateClient()
throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException {
// use the TrustSelfSignedStrategy to allow Self Signed Certificates
SSLContext sslContext = SSLContextBuilder
.create()
.loadTrustMaterial(new TrustSelfSignedStrategy())
.build();
// we can optionally disable hostname verification.
// if you don't want to further weaken the security, you don't have to include this.
HostnameVerifier allowAllHosts = new NoopHostnameVerifier();
// create an SSL Socket Factory to use the SSLContext with the trust self signed certificate strategy
// and allow all hosts verifier.
SSLConnectionSocketFactory connectionFactory = new SSLConnectionSocketFactory(sslContext, allowAllHosts);
// finally create the HttpClient using HttpClient factory methods and assign the ssl socket factory
return HttpClients
.custom()
.setSSLSocketFactory(connectionFactory)
.build();
}
23 回答
您需要使用自己的TrustManager创建SSLContext,并使用此上下文创建HTTPS方案 . 这是代码,
所有其他答案都已弃用或不适用于HttpClient 4.3 .
这是一种在构建http客户端时允许所有主机名的方法 .
或者,如果您使用的是4.4或更高版本,则更新的调用如下所示:
仅仅为了记录,有一个更简单的方法来实现与HttpClient 4.1相同
为了记录,使用httpclient 4.3.6测试并与流畅的api的Executor兼容:
对于Apache HttpClient 4.4:
这是从我们的实际工作实施中提取的 .
其他答案很受欢迎,但对于HttpClient 4.4,它们不起作用 . 我花了好几个小时尝试和耗尽可能性,但似乎已经有非常重要的API更改和重新定位4.4 .
另见一个稍微全面的解释:http://literatejava.com/networks/ignore-ssl-certificate-errors-apache-httpclient-4-4/
希望有所帮助!
只需要使用较新的 HttpClient 4.5 来执行此操作,看起来它们是适用于我并使用最新API的代码段:'ve deprecated a few things since 4.4 so here'
如果您想要做的就是摆脱无效的主机名错误,您可以这样做:
Apache HttpClient 4.5.5
没有使用过弃用的API .
简单可验证的测试用例:
我们正在使用HTTPClient 4.3.5并且我们尝试了几乎所有解决方案都存在于stackoverflow上但没有任何问题,在思考并找出问题之后,我们来看下面的代码,它完美地运行,只需在创建HttpClient实例之前添加它 .
这就是我做到的 -
创建我自己的MockSSLSocketFactory(下面附带的类)
用它来初始化DefaultHttpClient . 如果使用代理,则需要提供代理设置 .
初始化DefaultHTTPClient -
模拟SSL工厂 -
如果在代理后面,需要这样做 -
使用流畅的4.5.2我必须进行以下修改才能使其正常工作 .
在ZZ Coder's answer的扩展名中,覆盖hostnameverifier会很不错 .
要接受HttpClient 4.4.x中的所有证书,您可以在创建httpClient时使用以下一个线程:
Apache HttpClient 4.1.3的完整工作版本(基于上面的oleg代码,但它仍需要我系统上的allow_all_hostname_verifier):
注意我正在重新抛出所有异常,因为实际上,如果在真实系统中出现任何异常,我无能为力!
如果您使用的是fluent API,则需要通过
Executor
进行设置:...其中
sslContext
是创建的SSLContext,如_817179的答案所示 .之后,您可以执行以下http请求:
注意:使用HttpClient 4.2进行测试
测试4.3.3
}
测试4.5.4:
下面的代码适用于
4.5.5
代码输出是
浏览器输出是
使用的pom如下
使用Fluent API测试HttpClient 4.5.5
如果您在使用嵌入Apache HttpClient 4.1的AmazonS3Client时遇到此问题,您只需要定义这样的系统属性,以便放宽SSL证书检查程序:
-Dcom.amazonaws.sdk.disableCertChecking =真
恶作剧管理
fwiw,一个使用JAX-RS 2.x的“RestEasy”实现来构建一个特殊的“信任所有”客户端的例子......
related Maven dependencies
如果您使用 Apache httpClient 4.5.x ,请尝试以下操作: