通过HttpClient实现访问HTTPS网站

文章的HttpClient版本为3.

实现SSL访问有2种方法.

第一种方式是通过浏览器导出需要的证书,然后将证书运用到代码中使用.

第二种方式,实现SSL管理,直接接收服务器发送到证书.

本文只讨论第二种方式.

该方法具体是实现一个SecureProtocolSocketFactory处理SSL.

import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.UnknownHostException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.SocketFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.apache.commons.httpclient.ConnectTimeoutException;
import org.apache.commons.httpclient.params.HttpConnectionParams;
import org.apache.commons.httpclient.protocol.SecureProtocolSocketFactory;

/**
 * @author yansheng723@gmail.com
 */
public class MySecureProtocolSocketFactory implements SecureProtocolSocketFactory {  
    private SSLContext sslcontext = null;  
     
    private SSLContext createSSLContext() {  
        SSLContext sslcontext=null;  
        try {  
            sslcontext = SSLContext.getInstance("SSL");  
            sslcontext.init(null, new TrustManager[]{new TrustAnyTrustManager()}, new java.security.SecureRandom());  
        } catch (NoSuchAlgorithmException e) {  
            e.printStackTrace();  
        } catch (KeyManagementException e) {  
            e.printStackTrace();  
        }  
        return sslcontext;  
    }  
     
    private SSLContext getSSLContext() {  
        if (this.sslcontext == null) {  
            this.sslcontext = createSSLContext();  
        }  
        return this.sslcontext;  
    }  
     
    public Socket createSocket(Socket socket, String host, int port, boolean autoClose)  
            throws IOException, UnknownHostException {  
        return getSSLContext().getSocketFactory().createSocket(  
                socket,  
                host,  
                port,  
                autoClose  
            );  
    }  
  
    public Socket createSocket(String host, int port) throws IOException,  
            UnknownHostException {  
        return getSSLContext().getSocketFactory().createSocket(  
                host,  
                port  
            );  
    }  
     
     
    public Socket createSocket(String host, int port, InetAddress clientHost, int clientPort)  
            throws IOException, UnknownHostException {  
        return getSSLContext().getSocketFactory().createSocket(host, port, clientHost, clientPort);  
    }  
  
    public Socket createSocket(String host, int port, InetAddress localAddress,  
            int localPort, HttpConnectionParams params) throws IOException,  
            UnknownHostException, ConnectTimeoutException {  
        if (params == null) {  
            throw new IllegalArgumentException("Parameters may not be null");  
        }  
        int timeout = params.getConnectionTimeout();  
        SocketFactory socketfactory = getSSLContext().getSocketFactory();  
        if (timeout == 0) {  
            return socketfactory.createSocket(host, port, localAddress, localPort);  
        } else {  
            Socket socket = socketfactory.createSocket();  
            SocketAddress localaddr = new InetSocketAddress(localAddress, localPort);  
            SocketAddress remoteaddr = new InetSocketAddress(host, port);  
            socket.bind(localaddr);  
            socket.connect(remoteaddr, timeout);  
            return socket;  
        }  
    }  
     
    //自定义私有类  
    private static class TrustAnyTrustManager implements X509TrustManager {  
        
        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {  
        }  
    
        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {  
        }  
    
        public X509Certificate[] getAcceptedIssuers() {  
            return new X509Certificate[]{};  
        }  
    }     
  
}  

调用实现的Factory,注册到Protocol中

@SuppressWarnings("deprecation")
Protocol protocol = new Protocol("https", new
		MySecureProtocolSocketFactory (), 443) {
};
Protocol.registerProtocol("https", protocol);


HttpClient访问https网站的问题

09-08

我想用HttpClient访问一个https网站,我已经拥有服务端证书和客户端证书,我将服务端证号和客户端证号都导入到jdk的cacerts中,也按着网上的办法:rnhttpclient完全支持ssl连接方式。通常,如果不需要进行客户端认证和服务器端认证的ssl连接,httpclient的处理方式是和http方式完全一样。 rn现在这里是讲的是需要客户端认证数字证书时的httpclient处理方式(因为需要客户端认证时,连接会被主动关闭)。rn1。使用ie访问你要连结的url地址,这时你会看到弹出一个询问是否继续和服务器建立连接的对话框(安全警报)。选择“查看证书”->“详细信息”->“复制文件到”导出数字证书(例: server.cer或server.crt)。rn2。使用导出的数字证书来创建你的keystorernkeytool -import -alias "my server cert" -file server.cer -keystore my.truststorernkeytool -genkey -v -alias "my client key" -validity 365 -keystore my.keystorern3。在引入AuthSSLProtocolSocketFactory.java,AuthSSLX509TrustManager.java和AuthSSLInitializationError后在你的代码里按下面的例子里来进行ssl连接rnProtocol authhttps = new Protocol("https",rnnew AuthSSLProtocolSocketFactory(rnnew URL("file:my.keystore"), "mypassword",rnnew URL("file:my.truststore"), "mypassword"), 8443);rnHttpClient client = new HttpClient();rnclient.getHostConfiguration().setHost("sh.12530", 8443, authhttps);rn/*只能使用相对路径*/rnGetMethod httpget = new GetMethod("/");rnclient.executeMethod(httpget);rnrn执行后报错:rnjavax.net.ssl.SSLHandshakeException: Received fatal alert: handshake_failurern我确认程序是已经找到服务端证书了,可能在客户端认证的时候出错了,请问我错在哪了,怎么办?

没有更多推荐了,返回首页

私密
私密原因:
请选择设置私密原因
  • 广告
  • 抄袭
  • 版权
  • 政治
  • 色情
  • 无意义
  • 其他
其他原因:
120
出错啦
系统繁忙,请稍后再试