cn.cuizuoli.appranking.http.client.TrustSSLSocketFactoryFactoryBean.java Source code

Java tutorial

Introduction

Here is the source code for cn.cuizuoli.appranking.http.client.TrustSSLSocketFactoryFactoryBean.java

Source

/*
 * Copyright 2014 the original author or authors.
 *
 * Licensed 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.
 */
package cn.cuizuoli.appranking.http.client;

import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

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

import org.springframework.beans.factory.FactoryBean;

/**
 * TrustSSLSocketFactoryFactoryBean
 * @author cuizuoli
 */
public class TrustSSLSocketFactoryFactoryBean implements FactoryBean<SSLSocketFactory> {

    @Override
    public SSLSocketFactory getObject() throws Exception {
        try {
            SSLContext sc = SSLContext.getInstance("SSL");
            sc.init(null, new TrustManager[] { new TrustAnyTrustManager() }, new SecureRandom());
            return sc.getSocketFactory();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public Class<?> getObjectType() {
        return SSLSocketFactory.class;
    }

    @Override
    public boolean isSingleton() {
        return false;
    }

    /**
     * TrustAnyTrustManager
     * DaLian Software weibo-api
     * com.weibo.http.client.TrustSSLSocketFactoryFactoryBean.java
     * @author cuizuoli
     * @date 20131221
     */
    private class TrustAnyTrustManager implements X509TrustManager {
        @Override
        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }

        @Override
        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return new X509Certificate[] {};
        }
    }

}