https httpclient 请求不绕过 证书
程序员文章站
2022-05-16 12:22:27
...
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/
谢谢您的赞助,我会做的更好!