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/



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

 

目录
相关文章
|
1天前
|
网络协议 应用服务中间件 网络安全
免费泛域名https证书教程—无限免费续签
随着互联网安全意识提升,越来越多网站采用HTTPS协议。本文介绍如何通过JoySSL轻松获取并实现免费泛域名SSL证书的无限续签。JoySSL提供永久免费通配符SSL证书,支持无限制域名申请及自动续签,全中文界面适合国内用户。教程涵盖注册账号、选择证书类型、验证域名所有权、下载与安装证书以及设置自动续签等步骤,帮助网站简化SSL证书管理流程,确保长期安全性。
|
15天前
|
安全 算法 网络协议
ip地址https证书免费试用—政企单位专用
IP地址HTTPS证书为基于公网IP的服务提供加密保护,JoySSL等机构提供免费试用,帮助政企用户降低安全成本。用户需注册账号、申请证书、提交CSR并验证IP所有权,最后安装证书并测试。免费证书有效期短,但能有效保障数据安全,提升用户信任度及合规性。
|
11天前
|
安全 网络安全 数据安全/隐私保护
内网/局域网IP地址申请https证书方法
为内网/局域网IP地址申请HTTPS证书,可增强数据传输的安全性。首先确定固定的内网IP地址,选择可信的证书颁发机构,注册并申请免费或付费SSL证书,提交相关信息,支付费用(如有)。证书申请成功后,下载并配置于服务器,确保通过浏览器访问时显示为安全连接。注意定期更新证书,确保持续的安全保障。此过程适用于局域网内部通信加密,提升内网服务的安全水平。
|
19天前
|
安全 数据安全/隐私保护
IP地址https证书免费申请教程
本教程详细介绍如何免费申请IP地址HTTPS证书,涵盖准备、申请、审核、下载与部署阶段。从确认IP地址、选择CA、注册账户到验证控制权,最后完成证书部署,确保数据传输安全。注意证书有效期较短,需及时续签。
|
25天前
|
安全 物联网 数据建模
IP地址能否申请HTTPS证书?
IP地址可申请HTTPS证书,但需满足特定条件。首先,该IP须为公网IP,具备唯一性和可控性。证书类型限于DV或OV级别,不支持EV。申请过程包括所有权验证及端口开放。适用于服务器间通信及IoT设备等场景。申请时需注意成本、浏览器兼容性和安全性问题。
|
1月前
|
安全 应用服务中间件 网络安全
免费ip地址https证书申请方法
IP SSL证书用于保障IP地址与浏览器间的数据传输安全,多数需付费购买。JoySSL现提供免费试用版,申请流程包括:访问官网、注册账号(需输入特定注册码230922)、选择证书类型、填写申请信息、验证IP控制权、等待审核、下载及部署证书。确保IP地址独立可控,信息准确,及时续期。
|
1月前
|
安全 API 网络安全
使用OkHttp进行HTTPS请求的Kotlin实现
使用OkHttp进行HTTPS请求的Kotlin实现
|
1月前
|
安全 网络安全 数据安全/隐私保护
政务单位IP地址https证书
政务单位IP地址HTTPS证书是一种专为只有IP地址而无域名的政务网站设计的数字证书,用于加密通信、确保数据安全并提升用户信任度。申请流程包括选择证书颁发机构、提交申请并验证、部署证书等步骤。证书有效期通常为一年或多年,需定期更新以确保安全性。
|
1月前
|
算法 安全 网络安全
等保、密评使用的IP地址https证书
等保和密评是确保网络安全的重要环节。IP地址的HTTPS证书通过加密数据传输、符合等保密评要求、提升IP身份辨识度,起到关键作用。证书需国产化、支持国密算法,并建议采用OV或EV证书。申请流程包括准备、选择服务商、申请与验证、签发与部署、验证与测试。定期检查证书有效期,确保持续有效性。
|
2月前
|
存储 网络安全 对象存储
缺乏中间证书导致通过HTTPS协议访问OSS异常
【10月更文挑战第4天】缺乏中间证书导致通过HTTPS协议访问OSS异常
131 4
下一篇
DataWorks