https httpclient 请求不绕过 证书

简介: https  httpclient 请求不绕过 证书       import java.io.FileNotFoundException; import java.io.IOException; import java.

https  httpclient 请求不绕过 证书

 

 

 

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Set;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.conn.ssl.X509HostnameVerifier;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import com.management.oa.OaApplication;
import com.management.oa.common.ServiceError;
import com.management.oa.data.UserData;
import com.management.oa.data.json.QueryResultJson;
import com.management.oa.helper.JsonParser;
import com.management.oa.helper.PreferencesService;
import com.management.oa.utils.IsOneSessionUtil.MyHandler;

public class HttpsUtil {
    public static final String  IS_TRUSTED               = "isTrusted";
    private static final String SECURITY_CONNECTION_TYPE = "https";
    public static final String  HTTPS_FILE_NAME          = "client_keystore.bks";
    private static final String KEY_STORE_PASSWORD       = "654321";
    private static final String SSL_PROTOCAL             = "TLS";
    public static String        mHostIp;
    public static int           mHostPort;
    public static String        mHostPath;
    private static final int    LOG_CMD_ID               = 0;
    private static final int    mHttps_Time_Out          = 50000;

    /**
     * URL有效性验�?
     */
    private static boolean parseUrl( String strUrl ) {
        boolean ret = false;

        if ( strUrl != null ) {
            URL url;
            try {
                url = new URL( strUrl );
                mHostIp = url.getHost();
                mHostPort = url.getPort();

                ret = true;
            }
            catch ( MalformedURLException e ) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return ret;
    }

    /**
     * 用json上传和下载信�?
     */
    public static void getNetInfoByPost( final Context context,
            final String url, final String jsonStr, final String jsonType,
            final Handler handler ) {

        ThreadUtil.getTheadPool( true ).submit( new Runnable() {

            @Override
            public void run() {
                try {
                    HttpResponse resp;
                    HttpPost httpPost;

                    if ( url.startsWith( SECURITY_CONNECTION_TYPE ) ) {
                        httpPost = makeHttpPost( url );
                        resp = makeHttpsClient( context, handler ).execute(
                                httpPost );
                        if ( resp != null ) {
                            log_to_view( "StatusCode : "
                                    + resp.getStatusLine().getStatusCode(),
                                    handler );
                            log_to_view( "ReasonPhrase : "
                                    + resp.getStatusLine().getReasonPhrase(),
                                    handler );
                            log_to_view(
                                    "ProtocolVersion : "
                                            + resp.getStatusLine()
                                                    .getProtocolVersion(),
                                    handler );

                            log_to_view( "Content : "
                                    + resp.getEntity().getContentType(),
                                    handler );
                            log_to_view( "Content : "
                                    + resp.getEntity().getContentLength(),
                                    handler );
                            String strResult = EntityUtils.toString( resp
                                    .getEntity() );
                            log_to_view( "strResult : " + strResult, handler );

                        }
                        else {
                            log_to_view( "NULL", handler );
                        }
                    }
                    else {
                        httpPost = new HttpPost( url );
                        List<NameValuePair> pair = new ArrayList<NameValuePair>();
                        pair.add( new BasicNameValuePair( "type", jsonType ) );
                        pair.add( new BasicNameValuePair( "json", jsonStr ) );
                        httpPost.setEntity( new UrlEncodedFormEntity( pair,
                                "utf-8" ) );
                        resp = new DefaultHttpClient().execute( httpPost );
                        int statusCode = resp.getStatusLine().getStatusCode();
                        Message message = handler.obtainMessage();
                        message.what = statusCode;
                        if ( statusCode == HttpStatus.SC_OK ) {
                            String strResult = EntityUtils.toString( resp
                                    .getEntity() );
                            message.obj = strResult;
                        }
                        handler.sendMessage( message );
                    }

                }
                catch ( Exception e ) {
                    log_to_view( "Exception:" + e.getMessage(), handler );
                    handler.sendEmptyMessage( NetUtil.NET_EXC_ERR );
                }
            }
        } );
    }

    /**
     * 获得测试post
     */
    private static HttpPost makeHttpPost( String url ) {
        HttpPost httpPost = new HttpPost( url );
        httpPost.setHeader( "test", "test" );
        ArrayList<NameValuePair> loginInfo = new ArrayList<NameValuePair>();
        loginInfo.add( new BasicNameValuePair( "name", "peter" ) );
        try {
            httpPost.setEntity( new UrlEncodedFormEntity( loginInfo ) );
        }
        catch ( UnsupportedEncodingException e ) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        HttpParams timeParams = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout( timeParams, mHttps_Time_Out );
        HttpConnectionParams.setSoTimeout( timeParams, mHttps_Time_Out );
        httpPost.setParams( timeParams );
        return httpPost;
    }

    /**
     * 获得https client
     */
    private static HttpClient makeHttpsClient( Context context, Handler mHandler ) {
        try {

            KeyStore trustStore = KeyStore.getInstance( KeyStore
                    .getDefaultType() );
            trustStore.load( context.openFileInput( HTTPS_FILE_NAME ),
                    KEY_STORE_PASSWORD.toCharArray() );
            SSLSocketFactory socketFactory = new SSLSocketFactory( trustStore );
            socketFactory.setHostnameVerifier( new X509HostnameVerifier() {
                public boolean verify( String host, SSLSession session ) {
                    return true;
                }

                public void verify( String host, SSLSocket ssl )
                        throws IOException {
                }

                public void verify( String host, X509Certificate cert )
                        throws SSLException {
                }

                public void verify( String host, String[] cns,
                        String[] subjectAlts ) throws SSLException {
                }
            } );
            Scheme sch = new Scheme( SECURITY_CONNECTION_TYPE, socketFactory,
                    mHostPort );
            HttpClient httpClient = new DefaultHttpClient();
            httpClient.getConnectionManager().getSchemeRegistry()
                    .register( sch );
            return httpClient;
        }
        catch ( KeyStoreException e ) {
            log_to_view( e.getMessage(), mHandler );
        }
        catch ( NoSuchAlgorithmException e ) {
            log_to_view( e.getMessage(), mHandler );
        }
        catch ( CertificateException e ) {
            log_to_view( e.getMessage(), mHandler );
        }
        catch ( KeyManagementException e ) {
            log_to_view( e.getMessage(), mHandler );
        }
        catch ( UnrecoverableKeyException e ) {
            log_to_view( e.getMessage(), mHandler );
        }
        catch ( IOException e ) {
            log_to_view( e.getMessage(), mHandler );
        }
        return null;
    }

    @SuppressLint( "DefaultLocale" )
    public static void getNetInfoByPost( final Context context,
            final String strUrl, final HashMap<String, String> postInfo,
            final Handler handler, final String jsonInfo ) {
        Log.e( "HttpUtil-post", postInfo.toString());

        if ( !parseUrl( strUrl ) ) {
            return;
        }

        ThreadUtil.getTheadPool( true ).submit( new Runnable() {

            private PreferencesService mService;

            private boolean            mSecure;
            private HttpPost           mHttpPost;
            private HttpParams         mHttpParameters;
            private DefaultHttpClient  mHttpClient;

            private void makeHttpPost() {
                mHttpParameters = new BasicHttpParams();
                mHttpPost = new HttpPost( strUrl );
                if ( mSecure ) {
                    mService = PreferencesService.getInstance( context );
                    boolean isTrusted = mService.getBoolean( IS_TRUSTED, false );
                    if ( !isTrusted ) {
                        HttpsUtil.installCert( context, handler, mService );
                    }

                    // 设置超时时间
                    HttpConnectionParams.setConnectionTimeout( mHttpParameters,
                            mHttps_Time_Out );
                    HttpConnectionParams.setSoTimeout( mHttpParameters,
                            mHttps_Time_Out );
                }
                else {
                    // 设置超时时间
                    HttpConnectionParams.setConnectionTimeout( mHttpParameters,
                            NetUtil.CONNECT_TIMEOUT );
                    HttpConnectionParams.setSoTimeout( mHttpParameters, 30000 );
                }

                mHttpPost.setParams( mHttpParameters );
                mHttpPost.addHeader( "Cookie", postInfo.remove( "Cookie" ) );
            }

            private void makeHttpsClient() {
                try {
                    KeyStore trustStore = KeyStore.getInstance( KeyStore
                            .getDefaultType() );
                    trustStore.load( context.openFileInput( HTTPS_FILE_NAME ),
                            KEY_STORE_PASSWORD.toCharArray() );
                    SSLSocketFactory socketFactory = new SSLSocketFactory(
                            trustStore );
                    socketFactory
                            .setHostnameVerifier( new X509HostnameVerifier() {
                                public boolean verify( String host,
                                        SSLSession session ) {
                                    return true;
                                }

                                public void verify( String host, SSLSocket ssl )
                                        throws IOException {
                                }

                                public void verify( String host,
                                        X509Certificate cert )
                                        throws SSLException {
                                }

                                public void verify( String host, String[] cns,
                                        String[] subjectAlts )
                                        throws SSLException {
                                }
                            } );
                    Scheme sch = new Scheme( SECURITY_CONNECTION_TYPE,
                            socketFactory, mHostPort );
                    mHttpClient = new DefaultHttpClient();
                    mHttpClient.getConnectionManager().getSchemeRegistry()
                            .register( sch );
                    return;

                }
                catch ( KeyStoreException e ) {
                    log_to_view( e.getMessage(), handler );
                }
                catch ( NoSuchAlgorithmException e ) {
                    log_to_view( e.getMessage(), handler );
                }
                catch ( CertificateException e ) {
                    log_to_view( e.getMessage(), handler );
                }
                catch ( KeyManagementException e ) {
                    log_to_view( e.getMessage(), handler );
                }
                catch ( UnrecoverableKeyException e ) {
                    log_to_view( e.getMessage(), handler );
                }
                catch ( IOException e ) {

                    log_to_view( e.getMessage(), handler );
                }

                mHttpClient = null;
            }

            private void makeHttpClient() {
                if ( mSecure ) {
                    makeHttpsClient();
                }
                else {
                    mHttpClient = new DefaultHttpClient( mHttpParameters );
                }
            }

            @Override
            public void run() {
                try {
                    URL url = new URL( strUrl );
                    mSecure = url.getProtocol().toLowerCase()
                            .equals( SECURITY_CONNECTION_TYPE );

                    makeHttpPost();
                    makeHttpClient();

                    List<NameValuePair> nvps = new ArrayList<NameValuePair>();
                    HttpResponse response = null;

                    if ( postInfo != null && jsonInfo == null ) {
                        Set<String> keys = postInfo.keySet();
                        for ( String key : keys ) {
                            nvps.add( new BasicNameValuePair( key, postInfo
                                    .get( key ) ) );
                        }

                        UrlEncodedFormEntity urlEntity = new UrlEncodedFormEntity(
                                nvps, HTTP.UTF_8 );
                        mHttpPost.setEntity( urlEntity );
                    }
                    else if ( jsonInfo != null ) {
                        StringEntity entity = new StringEntity( jsonInfo,
                                HTTP.UTF_8 );
                        mHttpPost.setEntity( entity );
                    }

                    // mHttpPost.set
                    response = mHttpClient.execute( mHttpPost );

                    int statusCode = response.getStatusLine().getStatusCode();
                    Log.i( "httpsUtil", "statusCode =" + statusCode );
                    Message message = handler.obtainMessage();

                    if ( statusCode == HttpStatus.SC_OK
                            || statusCode == NetUtil.NET_QUERY_SUCC ) {
                        String backStr = EntityUtils.toString( response
                                .getEntity() );
                        message.obj = backStr;
//                        Log.e("message.obj" , backStr );
                    }
                   
                    if ( handler instanceof MyHandler ) {
                        // 保存用户信息
                        String ret = ( String ) message.obj;

                        if ( ret != null && ret.length() > 0 ) {
                            QueryResultJson result = JsonParser
                                    .parseQueryResultJson( ret );
                            if ( result != null ) {

                                if ( result.retcode == ServiceError.ERR_NONE ) {

                                    if ( result.retdata != null ) {
                                        PrefInfoUtils.saveLoginInfo(
                                                OaApplication.getmContext(),
                                                result.retdata.toString() );
                                        UserData.getInstance()
                                                .setLoginData(
                                                        PrefInfoUtils
                                                                .getLoginInfo( OaApplication
                                                                        .getmContext() ) );
                                    }
                                }
                            }
                        }
                    }
                    message.what = statusCode;
                    handler.sendMessage( message );
                }
                catch ( MalformedURLException e ) {
                    handler.sendEmptyMessage( NetUtil.NET_ERR );
                }
                catch ( UnsupportedEncodingException e ) {
                    handler.sendEmptyMessage( NetUtil.NET_ERR );

                }
                catch ( ClientProtocolException e ) {
                    handler.sendEmptyMessage( NetUtil.NET_ERR );
                }
                catch ( ParseException e ) {
                    handler.sendEmptyMessage( NetUtil.NET_ERR );
                }
                catch ( IOException e ) {
                    handler.sendEmptyMessage( NetUtil.NET_REQUEST_TIME_OUT );

                }
                catch ( Exception e ) {
                    Log.e( "httputil--post", "err" );
                    e.printStackTrace();
                }

            }
        } );
    }

    /**
     * 安装证书
     */
    public static void installCert( Context context, Handler mHandler,
            PreferencesService preferences ) {
        boolean istrusted = false;
        try {

            InputStream iStream = context.openFileInput( HTTPS_FILE_NAME );
            KeyStore ks = KeyStore.getInstance( KeyStore.getDefaultType() );
            ks.load( iStream, KEY_STORE_PASSWORD.toCharArray() );
            iStream.close();

            SSLContext sslContext = SSLContext.getInstance( SSL_PROTOCAL );
            TrustManagerFactory tmf = TrustManagerFactory
                    .getInstance( TrustManagerFactory.getDefaultAlgorithm() );
            tmf.init( ks );

            X509TrustManager defaultTrustManager = ( X509TrustManager ) tmf
                    .getTrustManagers()[0];
            SavingTrustManager tm = new SavingTrustManager( defaultTrustManager );
            sslContext.init( null, new TrustManager[] { tm }, null );
            javax.net.ssl.SSLSocketFactory factory = sslContext
                    .getSocketFactory();

            try {
                SSLSocket socket = ( SSLSocket ) factory.createSocket( mHostIp,
                        mHostPort );
                socket.setSoTimeout( mHttps_Time_Out );
                socket.startHandshake();
                socket.close();
                istrusted = true;
            }
            catch ( SSLException e ) {
                log_to_view( e.getMessage(), mHandler );
                istrusted = false;
            }
            if ( !istrusted ) {
                X509Certificate[] chain = tm.chain;
                if ( chain == null ) {
                    return;
                }
                ks.setCertificateEntry( mHostIp + "_" + 0, chain[0] );
                // 如果想更改新密码,这个passwd替换成新密码即可
                ks.store( context.openFileOutput( HTTPS_FILE_NAME,
                        Context.MODE_PRIVATE ), KEY_STORE_PASSWORD
                        .toCharArray() );
                istrusted = true;
            }

        }
        catch ( FileNotFoundException e ) {
            log_to_view( e.getMessage(), mHandler );
        }
        catch ( NoSuchAlgorithmException e ) {
            log_to_view( e.getMessage(), mHandler );
        }
        catch ( CertificateException e ) {
            log_to_view( e.getMessage(), mHandler );
        }
        catch ( IOException e ) {
            log_to_view( e.getMessage(), mHandler );
        }
        catch ( KeyStoreException e ) {
            log_to_view( e.getMessage(), mHandler );
        }
        catch ( KeyManagementException e ) {
            log_to_view( e.getMessage(), mHandler );
        }
        finally {
            preferences.putBoolean( IS_TRUSTED, istrusted );
        }
    }

    /**
     * 保存管理�?
     */
    private static class SavingTrustManager implements X509TrustManager {

        private final X509TrustManager tm;
        private X509Certificate[]      chain;

        SavingTrustManager( X509TrustManager tm ) {
            this.tm = tm;
        }

        public X509Certificate[] getAcceptedIssuers() {
            throw new UnsupportedOperationException();
        }

        public void checkClientTrusted( X509Certificate[] chain, String authType )
                throws CertificateException {
            throw new UnsupportedOperationException();
        }

        public void checkServerTrusted( X509Certificate[] chain, String authType )
                throws CertificateException {
            this.chain = chain;
            tm.checkServerTrusted( chain, authType );
        }
    }

    /**
     * 导出日志
     */
    private static void log_to_view( String logs, Handler mHandler ) {
        Bundle b = new Bundle();
        b.putString( "log", logs );
        Message m = Message.obtain( mHandler, LOG_CMD_ID );
        m.setData( b );
        m.sendToTarget();
    }

    /**
     * 流拷�?
     */
    public static void copyStream( InputStream iStream, OutputStream oStream )
            throws Exception {
        byte[] buff = new byte[1024];
        int len = iStream.read( buff );
        while ( len != -1 ) {
            oStream.write( buff, 0, len );
            len = iStream.read( buff );
        }
    }
}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

捐助开发者 

在兴趣的驱动下,写一个免费的东西,有欣喜,也还有汗水,希望你喜欢我的作品,同时也能支持一下。 当然,有钱捧个钱场(支持支付宝和微信 以及扣扣群),没钱捧个人场,谢谢各位。

 

个人主页http://knight-black-bob.iteye.com/



 
 
 谢谢您的赞助,我会做的更好!

 

目录
相关文章
|
19天前
|
安全 算法 网络协议
解析:HTTPS通过SSL/TLS证书加密的原理与逻辑
HTTPS通过SSL/TLS证书加密,结合对称与非对称加密及数字证书验证实现安全通信。首先,服务器发送含公钥的数字证书,客户端验证其合法性后生成随机数并用公钥加密发送给服务器,双方据此生成相同的对称密钥。后续通信使用对称加密确保高效性和安全性。同时,数字证书验证服务器身份,防止中间人攻击;哈希算法和数字签名确保数据完整性,防止篡改。整个流程保障了身份认证、数据加密和完整性保护。
|
2月前
|
运维 搜索推荐 安全
HTTPS 证书自动化运维:基础知识与重要性
随着互联网发展,HTTPS 成为保护网站和用户数据安全的标准协议。HTTPS 证书(SSL/TLS)验证网站身份并加密通信,分为 DV、OV 和 EV 三种类型,确保数据传输安全。它不仅提高安全性、增强用户信任,还能提升搜索引擎排名。手动管理证书繁琐易错,自动化运维工具如 Let`s Encrypt 和 Certbot 可简化流程,减少错误,提高效率。文章介绍了 HTTPS 证书的基础知识、重要性及自动化运维的概念。
|
2月前
|
监控 运维
HTTPS 证书自动化运维:https证书管理系统- 自动化监控
本文介绍如何设置和查看域名或证书监控。步骤1:根据证书状态选择新增域名或证书监控,线上部署推荐域名监控,未部署选择证书监控。步骤2:查询监控记录详情。步骤3:在详情页查看每日定时检测结果或手动测试。
HTTPS 证书自动化运维:https证书管理系统- 自动化监控
|
2月前
|
Linux 持续交付 调度
HTTPS 证书自动化运维:https证书管理系统-自动化部署
本指南介绍如何部署Linux服务器节点。首先复制生成的Linux脚本命令,然后将其粘贴到目标服务器上运行。接着刷新页面查看节点记录,并点击“配置证书”选择证书以自动部署。最后,节点部署完成,后续将自动调度,无需人工干预。
HTTPS 证书自动化运维:https证书管理系统-自动化部署
|
2月前
|
运维
HTTPS 证书自动化运维:https证书管理系统之自动化签发
通过访问【https://www.lingyanspace.com】注册账户,进入证书服务菜单并新增证书。填写域名(单域名、多域名或泛域名),创建订单后添加云解析DNS记录进行质检。确认完成后可下载证书,并支持后续查看、更新和定时更新功能。证书过期前15天自动更新,需配置邮箱接收通知。
HTTPS 证书自动化运维:https证书管理系统之自动化签发
|
2月前
|
机器学习/深度学习 人工智能 运维
HTTPS 证书自动化运维:展望未来发展趋势
HTTPS证书自动化运维正朝着更智能、高效和安全的方向发展。未来系统将提升自动化程度,减少人工干预,实现自动签发、续订与部署;深度集成多云平台,提供无缝管理体验;增强高级安全功能如加密算法和威胁检测;优化用户界面,降低使用门槛;支持更多操作系统,确保跨平台一致性;引入AI/ML技术,预测需求并自动解决问题;加强标准化与互操作性,促进生态系统协作。同时,系统将持续扩展功能、优化性能、支持国际化,并注重用户反馈,为全球用户提供优质的证书管理服务。
|
2月前
|
运维 监控 数据安全/隐私保护
HTTPS 证书自动化运维:HTTPS 证书管理系统之使用指南
本文详细介绍【灵燕空间HTTPS证书管理系统】(https://www.lingyanspace.com)的配置与使用,涵盖注册账户、邮箱配置及证书自动签发、监控和部署的一体化指南。通过页面顶部菜单的【视频教程】和【图文教程】,帮助用户从注册到实际应用全面掌握系统操作。最新迭代后,泛域名证书已包含根域名,无需额外申请多域名证书。
|
2月前
|
数据建模 网络安全
IP地址https证书最新申请流程步骤
确保信息准确,遵循CA指导,遇到问题可联系客服。
|
2月前
|
运维 监控 安全
HTTPS 证书自动化运维:HTTPS 证书管理系统之优势对比
本文详细介绍了一款功能强大的HTTPS证书管理系统,涵盖自动签发、更新、实时监控、部署一体化、自定义加密算法、集中管理和邮箱通知等功能。系统通过简化配置、智能引导、快速响应和多重防护等优势,确保企业和个人用户能高效、安全地管理证书,提升网站和应用的安全性。
|
2月前
|
运维 监控 安全
HTTPS 证书自动化运维:使用Certbot来申请https证书实践指南
本文深入探讨HTTPS证书自动化运维,提供实践指南与案例分析。首先介绍选择合适的工具和平台,如Certbot、ACME客户端及图形化管理系统的应用。接着详细讲解使用Certbot签发Let’s Encrypt证书的步骤,并强调安全策略、权限管理和监控日志的重要性。通过中小型企业与大型电商平台的实际案例,展示自动化运维的优势。最后针对常见问题提供解决方案,帮助读者实现高效、安全的证书管理。