- 浏览: 520101 次
- 性别:
- 来自: 北京
文章分类
- 全部博客 (422)
- 重要 (12)
- BUG解决备忘录 (32)
- 环境搭建 (17)
- 开源组件 (4)
- 数据库 (16)
- 设计模式 (4)
- 测试 (3)
- javascript (5)
- Android (14)
- jdk相关 (9)
- struts2 (10)
- freemark (3)
- 自定义扩展及工具类 (5)
- jdk5新特性及java基础 (13)
- ssh及其他框架 (15)
- linux (32)
- tcp-ip http协议 (8)
- 服务器集群与负载均衡 (34)
- 项目管理相关 (11)
- 实用小技术 (10)
- 架构相关 (14)
- firefox组件 (11)
- spider (6)
- 产品设计 (11)
- PHP (1)
- ws (4)
- lucene (10)
- 其他 (2)
- BI (1)
- NoSQL (3)
- gzip (1)
- ext (4)
- db (6)
- socket (1)
- 源码阅读 (2)
- NIO (2)
- 图片处理 (1)
- java 环境 (2)
- 项目管理 (4)
- 从程序员到项目经理(一):没有捷径 (1)
- bug (1)
- JAVA BASE (8)
- 技术原理 (0)
- 新框架新技术 (1)
- 量化与python (1)
- 系统编程 (0)
- C语言 (0)
- 汇编 (0)
- 算法 (0)
最新评论
-
hyspace:
别逗了,最后一个算法根本不是最优的,sort(function ...
数组去重——一道前端校招试题 -
washingtin:
楼主能把策略和路由的类代码贴出来吗
Spring + iBatis 的多库横向切分简易解决思路 -
sdyjmc:
初略看了一下,没有闹明白啊,均衡负载使用Nginx,sessi ...
J2EE集群原理 I -
shandeai520:
谢谢大神!请教大神一个问题:假如我有三台服务器,连接池的上限是 ...
集群和数据库负载均衡的研究 -
hekuilove:
给lz推荐一下apache commonsStringUtil ...
request 获取 ip
用了大半天时间才了解如何使用httpclient来进行https访问,现记录,已备后忘。
httpclient完全支持ssl连接方式。通常,如果不需要进行客户端认证和服务器端认证的ssl连接,httpclient的处理方式是和http方式完全一样。
现在这里是讲的是需要客户端认证数字证书时的httpclient处理方式(因为需要客户端认证时,连接会被主动关闭)。
1。使用ie访问你要连结的url地址,这时你会看到弹出一个询问是否继续和服务器建立连接的对话框(安全警报)。选择“查看证书”->“详细信息”->“复制文件到”导出数字证书(例: server.cer或server.crt)。
2。使用导出的数字证书来创建你的keystore
keytool -import -alias "my server cert" -file server.cer -keystore my.truststore
keytool -genkey -v -alias "my client key" -validity 365 -keystore my.keystore
3。在引入AuthSSLProtocolSocketFactory.java,AuthSSLX509TrustManager.java和AuthSSLInitializationError后在你的代码里按下面的例子里来进行ssl连接
Protocol authhttps = new Protocol("https",
new AuthSSLProtocolSocketFactory(
new URL("file:my.keystore"), "mypassword",
new URL("file:my.truststore"), "mypassword"), 8443);
HttpClient client = new HttpClient();
client.getHostConfiguration().setHost("sh.12530", 8443, authhttps);
/*只能使用相对路径*/
GetMethod httpget = new GetMethod("/");
client.executeMethod(httpget);
附录:
AuthSSLInitializationError.java
public class AuthSSLInitializationError extends Error {
/**
* 构招一个AuthSSLInitializationError实例
*/
public AuthSSLInitializationError() {
super();
}
/**
* 用指定信息构造一个AuthSSLInitializationError实例
* @param message
*/
public AuthSSLInitializationError(String message) {
super(message);
}
}
AuthSSLX509TrustManager.java
import java.security.cert.X509Certificate;
import com.sun.net.ssl.X509TrustManager;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public class AuthSSLX509TrustManager implements X509TrustManager
{
private X509TrustManager defaultTrustManager = null;
/** Log object for this class. */
private static final Log LOG = LogFactory.getLog(AuthSSLX509TrustManager.class);
/**
* Constructor for AuthSSLX509TrustManager.
*/
public AuthSSLX509TrustManager(final X509TrustManager defaultTrustManager) {
super();
if (defaultTrustManager == null) {
throw new IllegalArgumentException("Trust manager may not be null");
}
this.defaultTrustManager = defaultTrustManager;
}
/**
* @see com.sun.net.ssl.X509TrustManager#isClientTrusted(X509Certificate[])
*/
public boolean isClientTrusted(X509Certificate[] certificates) {
if (LOG.isInfoEnabled() && certificates != null) {
for (int c = 0; c < certificates.length; c++) {
X509Certificate cert = certificates[c];
LOG.info(" Client certificate " + (c + 1) + ":");
LOG.info(" Subject DN: " + cert.getSubjectDN());
LOG.info(" Signature Algorithm: " + cert.getSigAlgName());
LOG.info(" Valid from: " + cert.getNotBefore() );
LOG.info(" Valid until: " + cert.getNotAfter());
LOG.info(" Issuer: " + cert.getIssuerDN());
}
}
return this.defaultTrustManager.isClientTrusted(certificates);
}
/**
* @see com.sun.net.ssl.X509TrustManager#isServerTrusted(X509Certificate[])
*/
public boolean isServerTrusted(X509Certificate[] certificates) {
if (LOG.isInfoEnabled() && certificates != null) {
for (int c = 0; c < certificates.length; c++) {
X509Certificate cert = certificates[c];
LOG.info(" Server certificate " + (c + 1) + ":");
LOG.info(" Subject DN: " + cert.getSubjectDN());
LOG.info(" Signature Algorithm: " + cert.getSigAlgName());
LOG.info(" Valid from: " + cert.getNotBefore() );
LOG.info(" Valid until: " + cert.getNotAfter());
LOG.info(" Issuer: " + cert.getIssuerDN());
}
}
return this.defaultTrustManager.isServerTrusted(certificates);
}
/**
* @see com.sun.net.ssl.X509TrustManager#getAcceptedIssuers()
*/
public X509Certificate[] getAcceptedIssuers() {
return this.defaultTrustManager.getAcceptedIssuers();
}
}
AuthSSLProtocolSocketFactory .java
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.net.URL;
import java.net.UnknownHostException;
import java.security.GeneralSecurityException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Enumeration;
import org.apache.commons.httpclient.ConnectTimeoutException;
import org.apache.commons.httpclient.params.HttpConnectionParams;
import org.apache.commons.httpclient.protocol.ControllerThreadSocketFactory;
import org.apache.commons.httpclient.protocol.SecureProtocolSocketFactory;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.sun.net.ssl.KeyManager;
import com.sun.net.ssl.KeyManagerFactory;
import com.sun.net.ssl.SSLContext;
import com.sun.net.ssl.TrustManager;
import com.sun.net.ssl.TrustManagerFactory;
import com.sun.net.ssl.X509TrustManager;
public class AuthSSLProtocolSocketFactory implements SecureProtocolSocketFactory {
/** Log object for this class. */
private static final Log LOG = LogFactory.getLog(AuthSSLProtocolSocketFactory.class);
private URL keystoreUrl = null;
private String keystorePassword = null;
private URL truststoreUrl = null;
private String truststorePassword = null;
private SSLContext sslcontext = null;
/**
* Constructor for AuthSSLProtocolSocketFactory. Either a keystore or truststore file
* must be given. Otherwise SSL context initialization error will result.
*
* @param keystoreUrl URL of the keystore file. May be <tt>null</tt> if HTTPS client
* authentication is not to be used.
* @param keystorePassword Password to unlock the keystore. IMPORTANT: this implementation
* assumes that the same password is used to protect the key and the keystore itself.
* @param truststoreUrl URL of the truststore file. May be <tt>null</tt> if HTTPS server
* authentication is not to be used.
* @param truststorePassword Password to unlock the truststore.
*/
public AuthSSLProtocolSocketFactory(
final URL keystoreUrl, final String keystorePassword,
final URL truststoreUrl, final String truststorePassword)
{
super();
this.keystoreUrl = keystoreUrl;
this.keystorePassword = keystorePassword;
this.truststoreUrl = truststoreUrl;
this.truststorePassword = truststorePassword;
}
private static KeyStore createKeyStore(final URL url, final String password)
throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException
{
if (url == null) {
throw new IllegalArgumentException("Keystore url may not be null");
}
LOG.debug("Initializing key store");
KeyStore keystore = KeyStore.getInstance("jks");
keystore.load(url.openStream(), password != null ? password.toCharArray(): null);
return keystore;
}
private static KeyManager[] createKeyManagers(final KeyStore keystore, final String password)
throws KeyStoreException, NoSuchAlgorithmException, UnrecoverableKeyException
{
if (keystore == null) {
throw new IllegalArgumentException("Keystore may not be null");
}
LOG.debug("Initializing key manager");
KeyManagerFactory kmfactory = KeyManagerFactory.getInstance(
KeyManagerFactory.getDefaultAlgorithm());
kmfactory.init(keystore, password != null ? password.toCharArray(): null);
return kmfactory.getKeyManagers();
}
private static TrustManager[] createTrustManagers(final KeyStore keystore)
throws KeyStoreException, NoSuchAlgorithmException
{
if (keystore == null) {
throw new IllegalArgumentException("Keystore may not be null");
}
LOG.debug("Initializing trust manager");
TrustManagerFactory tmfactory = TrustManagerFactory.getInstance(
TrustManagerFactory.getDefaultAlgorithm());
tmfactory.init(keystore);
TrustManager[] trustmanagers = tmfactory.getTrustManagers();
for (int i = 0; i < trustmanagers.length; i++) {
if (trustmanagers[i] instanceof X509TrustManager) {
trustmanagers[i] = new AuthSSLX509TrustManager(
(X509TrustManager)trustmanagers[i]);
}
}
return trustmanagers;
}
private SSLContext createSSLContext() {
try {
KeyManager[] keymanagers = null;
TrustManager[] trustmanagers = null;
if (this.keystoreUrl != null) {
KeyStore keystore = createKeyStore(this.keystoreUrl, this.keystorePassword);
if (LOG.isDebugEnabled()) {
Enumeration aliases = keystore.aliases();
while (aliases.hasMoreElements()) {
String alias = (String)aliases.nextElement();
Certificate[] certs = keystore.getCertificateChain(alias);
if (certs != null) {
LOG.debug("Certificate chain '" + alias + "':");
for (int c = 0; c < certs.length; c++) {
if (certs[c] instanceof X509Certificate) {
X509Certificate cert = (X509Certificate)certs[c];
LOG.debug(" Certificate " + (c + 1) + ":");
LOG.debug(" Subject DN: " + cert.getSubjectDN());
LOG.debug(" Signature Algorithm: " + cert.getSigAlgName());
LOG.debug(" Valid from: " + cert.getNotBefore() );
LOG.debug(" Valid until: " + cert.getNotAfter());
LOG.debug(" Issuer: " + cert.getIssuerDN());
}
}
}
}
}
keymanagers = createKeyManagers(keystore, this.keystorePassword);
}
if (this.truststoreUrl != null) {
KeyStore keystore = createKeyStore(this.truststoreUrl, this.truststorePassword);
if (LOG.isDebugEnabled()) {
Enumeration aliases = keystore.aliases();
while (aliases.hasMoreElements()) {
String alias = (String)aliases.nextElement();
LOG.debug("Trusted certificate '" + alias + "':");
Certificate trustedcert = keystore.getCertificate(alias);
if (trustedcert != null && trustedcert instanceof X509Certificate) {
X509Certificate cert = (X509Certificate)trustedcert;
LOG.debug(" Subject DN: " + cert.getSubjectDN());
LOG.debug(" Signature Algorithm: " + cert.getSigAlgName());
LOG.debug(" Valid from: " + cert.getNotBefore() );
LOG.debug(" Valid until: " + cert.getNotAfter());
LOG.debug(" Issuer: " + cert.getIssuerDN());
}
}
}
trustmanagers = createTrustManagers(keystore);
}
SSLContext sslcontext = SSLContext.getInstance("SSL");
sslcontext.init(keymanagers, trustmanagers, null);
return sslcontext;
} catch (NoSuchAlgorithmException e) {
LOG.error(e.getMessage(), e);
throw new AuthSSLInitializationError("Unsupported algorithm exception: " + e.getMessage());
} catch (KeyStoreException e) {
LOG.error(e.getMessage(), e);
throw new AuthSSLInitializationError("Keystore exception: " + e.getMessage());
} catch (GeneralSecurityException e) {
LOG.error(e.getMessage(), e);
throw new AuthSSLInitializationError("Key management exception: " + e.getMessage());
} catch (IOException e) {
LOG.error(e.getMessage(), e);
throw new AuthSSLInitializationError("I/O error reading keystore/truststore file: " + e.getMessage());
}
}
private SSLContext getSSLContext() {
if (this.sslcontext == null) {
this.sslcontext = createSSLContext();
}
return this.sslcontext;
}
/**
* Attempts to get a new socket connection to the given host within the given time limit.
* <p>
* To circumvent the limitations of older JREs that do not support connect timeout a
* controller thread is executed. The controller thread attempts to create a new socket
* within the given limit of time. If socket constructor does not return until the
* timeout expires, the controller terminates and throws an {@link
ConnectTimeoutException}
* </p>
*
* @param host the host name/IP
* @param port the port on the host
* @param clientHost the local host name/IP to bind the socket to
* @param clientPort the port on the local machine
* @param params {@link
HttpConnectionParams Http connection parameters}
*
* @return Socket a new socket
*
* @throws IOException if an I/O error occurs while creating the socket
* @throws UnknownHostException if the IP address of the host cannot be
* determined
*/
public Socket createSocket(
final String host,
final int port,
final InetAddress localAddress,
final int localPort,
final HttpConnectionParams params
) throws IOException, UnknownHostException, ConnectTimeoutException {
if (params == null) {
throw new IllegalArgumentException("Parameters may not be null");
}
int timeout = params.getConnectionTimeout();
if (timeout == 0) {
return createSocket(host, port, localAddress, localPort);
} else {
// To be eventually deprecated when migrated to Java 1.4 or above
return ControllerThreadSocketFactory.createSocket(
this, host, port, localAddress, localPort, timeout);
}
}
/**
* @see SecureProtocolSocketFactory#createSocket(java.lang.String,int,java.net.InetAddress,int)
*/
public Socket createSocket(
String host,
int port,
InetAddress clientHost,
int clientPort)
throws IOException, UnknownHostException
{
return getSSLContext().getSocketFactory().createSocket(
host,
port,
clientHost,
clientPort
);
}
/**
* @see SecureProtocolSocketFactory#createSocket(java.lang.String,int)
*/
public Socket createSocket(String host, int port)
throws IOException, UnknownHostException
{
return getSSLContext().getSocketFactory().createSocket(
host,
port
);
}
/**
* @see SecureProtocolSocketFactory#createSocket(java.net.Socket,java.lang.String,int,boolean)
*/
public Socket createSocket(
Socket socket,
String host,
int port,
boolean autoClose)
throws IOException, UnknownHostException
{
return getSSLContext().getSocketFactory().createSocket(
socket,
host,
port,
autoClose
);
}
}
================================================================文章2
package
com.ipmotor.sm.db;
import
java.io.BufferedReader;
import
java.io.File;
import
java.io.FileInputStream;
import
java.io.InputStream;
import
java.io.InputStreamReader;
import
java.security.KeyStore;
import
org.apache.http.HttpResponse;
import
org.apache.http.client.HttpClient;
import
org.apache.http.client.methods.HttpGet;
import
org.apache.http.conn.scheme.Scheme;
import
org.apache.http.conn.ssl.SSLSocketFactory;
import
org.apache.http.impl.client.DefaultHttpClient;
/**
* 利用HttpClient,模拟https连接
* 使用4.1版本
*
@since
2011.7.7
*/
public
class
Test{
/**
* 运行主方法
*
@param
args
*
@throws
Exception
*/
public
static
void
main(String[] args)
throws
Exception {
//
获得httpclient对象
HttpClient httpclient
=
new
DefaultHttpClient();
//
获得密匙库
KeyStore trustStore
=
KeyStore.getInstance(KeyStore.getDefaultType());
FileInputStream instream
=
new
FileInputStream(
new
File(
"
D:/zzaa
"
));
//
密匙库的密码
trustStore.load(instream,
"
123456
"
.toCharArray());
//
注册密匙库
SSLSocketFactory socketFactory
=
new
SSLSocketFactory(trustStore);
//
不校验域名
socketFactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
Scheme sch
=
new
Scheme(
"
https
"
,
800
, socketFactory);
httpclient.getConnectionManager().getSchemeRegistry().register(sch);
//
获得HttpGet对象
HttpGet httpGet
=
null
;
httpGet
=
new
HttpGet(
"
https://10.15.32.176:800/cgi-bin/service.cgi?session=caef0c3742c8f8ef4c98772e860c9fd2&rand=128&domain=sun.com&type=domain&cmd=disable
"
);
//
发送请求
HttpResponse response
=
httpclient.execute(httpGet);
//
输出返回值
InputStream is
=
response.getEntity().getContent();
BufferedReader br
=
new
BufferedReader(
new
InputStreamReader(is));
String line
=
""
;
while
((line
=
br.readLine())
!=
null
){
System.out.println(line);
}
}
}
依赖的jar包
commons-codec-1.4.jar
commons-logging-1.1.1.jar
httpclient-4.1.1.jar
httpclient-cache-4.1.1.jar
httpcore-4.1.jar
httpmime-4.1.1.jar
发表评论
-
request 获取 ip
2013-02-18 10:47 1121public String getIpAddr(HttpSer ... -
HttpClient请求Https协议
2012-01-18 09:56 1920HttpClient请求Https协议 ... -
HttpServletRequest常用获取URL的方法
2011-12-31 10:35 16601、request.getRequestURL ... -
同一应用中http与https相互转换的过程 分享
2011-12-31 10:13 12321 基本信息 摘要: 本文中详细的描述 ... -
偶也研究OSGi
2010-12-07 09:52 1046偶也开始研究OSGi了,这东西真不错。不过官方的OSGi标 ... -
TCP握手协议
2010-12-01 00:22 925在TCP/IP协议中,TCP协议提供可靠的连接服务,采用三次握 ... -
http协议
2010-09-09 22:25 1044HTTP协议详解(真的很经典) 转自:http://blo ...
相关推荐
使用HttpClient4.5实现https请求忽略SSL证书验证工具类
标题中的“使用httpClient访问https+443端口号”指的是使用Apache HttpClient库来发起HTTPS(安全超文本传输协议)请求,目标服务器的默认端口是443。HTTPS是一种基于SSL/TLS的安全通信协议,用于在客户端和服务器...
不会的可以在评论区留言哈,这是我自己做项目用到的。所以绝对可用!同时共享出来给到大家
总结,通过以上步骤,我们已经成功配置了HttpClient 4.1以支持HTTPS访问。在实际应用中,你需要考虑更多的安全因素,比如证书的验证、安全策略等,以确保通信的安全性。同时,对于复杂的网络环境,可能还需要配置...
HttpClient之Https应用实例~ 包含: HttpClient 使用代理访问Https HttpClient 信任所有主机-对于任何证书都不做检查 HttpClient 允许所有证书的校验(包括过期证书)
本篇文章将详细讲解如何在HTTPClient 4.5版本中绕过SSL(Secure Sockets Layer)认证,实现对HTTPS网站的访问。 首先,了解SSL/TLS(Transport Layer Security)协议的重要性。SSL/TLS是网络安全传输的标准,它通过...
android HttpClient访问某些Https时,出现了问题,无法访问,好像是要安全验证。此Demo解决了此问题,HttpClient能够Https和Http类型的URL了。 在eclipse下打开工程若有乱码,请把eclipse的字符编码改成UTF-8。
本文将详细介绍如何使用`HttpClient`和`HttpsURLConnection`两种方式来访问HTTPS网站,包括验证证书和不验证证书的实现方法。 ### 1. Android中的HttpClient `HttpClient`是Apache提供的一种HTTP客户端库,它支持...
本篇文章将详细探讨如何使用HttpClient来访问Servlet,并阐述相关的核心知识点。 首先,我们需要理解Servlet的本质。Servlet是一种Java类,它扩展了服务器的功能,用于处理HTTP请求并生成响应。通常,Servlet部署在...
总结来说,处理需要客户端认证的HTTPS接口需要理解SSL/TLS协议、HttpClient的内部工作原理以及如何自定义安全配置。通过`InstallCert.java`和`HTTPSSecureProtocolSocketFactory.java`这两个文件,我们可以实现这个...
"JAVA利用HttpClient进行HTTPS接口调用的方法" 知识点1:HttpClient的基本概念 HttpClient是一个开放源代码的Java库,用于提供高效、灵活和可扩展的HTTP客户端解决方案。HttpClient支持HTTP/1.1和HTTP/2.0协议,...
另外在项目中正好需要访问https协议的接口,而对应的服务器没有购买商业CA颁发的正式受信证书,只是做了个自签名(联想一下12306网站购票时提示的那个警告信息),默认情况下通过HttpClient访问会抛出异常。...
这篇名为“简单的httpClient访问”的博文可能是介绍如何使用HttpClient进行基础的HTTP请求。HttpClient库提供了丰富的功能,包括GET、POST请求,设置请求头,处理响应,以及支持HTTPS等。接下来,我们将深入探讨...
本文会针对我们在编写HTTP客户端程序时经常碰到的几个问题进行分别介绍如何使用httpclient来解决它们,为了让读者更快的熟悉这个项目我们最开始先给出一个简单的例子来读取一个网页的内容,然后循序渐进解决掉前进中...
接下来,我们来看在Titanium中如何使用HttpClient访问REST服务。以下是一个基本的示例: ```javascript var http = Ti.Network.HTTPClient; var url = 'http://example.com/api/resource'; http.onload = function...
在本节中,我们将介绍如何使用HttpClient库来处理Cookie和HTTPS请求。 ```java package http.demo; import java.io.IOException; import org.apache.commons.httpclient.*; import org.apache.commons.httpclient....
HttpClientHelper 对这个类进行了封装,使得开发者无需直接与HttpClient接口打交道,而是通过更简洁、易用的方法调用来实现网络通信。这提高了代码的可读性和可维护性。 单例模式是软件设计模式的一种,确保一个类...
HttpClient是Apache基金会开发的一个...总的来说,HttpClient4是Java开发者进行HTTP通信的强大工具,通过代理访问网页只是其众多功能之一。理解并熟练使用HttpClient4,可以极大地提高我们处理网络请求的效率和灵活性。
总的来说,这个压缩包提供的`keytool`和`httpclient`相关JAR文件是进行安全的HTTPS通信的基础。理解如何正确使用这些工具和库,对于任何涉及网络通信的Java应用来说,都是提升安全性的重要步骤。正确配置和使用这些...