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/
谢谢您的赞助,我会做的更好!
相关推荐
HTTPClient 4.5中提供了这样的功能,可以让我们自定义SSL上下文,从而绕过默认的证书验证。以下是如何操作的步骤: 1. **创建自定义的X509TrustManager**:这个类负责验证服务器证书。我们可以创建一个信任所有证书...
下面是如何在Java中实现HTTPS请求并跳过证书验证: 1. 创建一个TrustManager,它总是信任所有证书,不进行任何验证: ```java TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { ...
总之,`httpclient`库提供了绕过HTTPS证书校验的能力,这在特定场景下很有用。然而,这种做法应该谨慎使用,并且只限于测试和非生产环境,因为这会削弱原本的加密保护,使数据易受攻击。在实际应用中,应确保使用...
通过创建自定义的SSLContext和HostnameVerifier,我们可以轻松地绕过SSL校验,从而简化接口调用流程。然而,这必须谨慎使用,避免在生产环境中引入安全风险。在apitest文件中,你可以找到包含HttpClient工具类代码,...
httpClient4.5配置SSL绕过https证书,httpClient过时替代方法-附件资源
但在开发或测试环境中,我们可能需要绕过这一环节。以下是如何配置HttpClient忽略SSL验证: 1. 创建自定义的`SSLSocketFactory`: 首先,创建一个不检查主机名的`SSLContext`: ```java SSLContext sslContext =...
在开发和测试环境中,我们可能需要绕过这个检查,以接受任何证书,这就涉及到HttpClient的SSLContext和TrustManager的配置。 以下是一个示例代码,展示了如何配置HttpClient以自动接受所有https证书: ```java ...
以上就是解决Java中HTTPS请求证书问题的详细步骤,以及如何使用httpUtils(以Apache HttpClient为例)进行HTTPS请求。通过这些方法,你可以确保与不信任证书的服务器安全通信。记住,处理证书时务必小心,避免引入...
但在开发环境中,为了快速测试,我们可能希望绕过这些认证。本文将详细介绍如何使用Java和HttpClient来模拟HTTPS文件上传,并跳过SSL验证。 首先,我们需要导入必要的依赖。如果你使用的是Maven项目,可以在pom.xml...
- **安全性问题**:绕过证书验证虽然简化了开发流程,但在生产环境中可能导致安全风险。建议使用有效的证书验证机制。 - **编码问题**:确保参数编码为UTF-8,以避免字符编码错误。 - **异常处理**:适当处理可能抛...
这样一来,即便目标服务器使用的是自签名的证书,也可以将这些证书直接传递给HttpClient,从而绕过证书验证的常规流程。 文章中提供的代码示例显示了如何实现上述两种方法。首先,创建了一个HttpClientHandler实例...
在这个过程中,我们创建了一个自定义的SSLClient类,绕过了证书验证,然后编写了PostRequestSender类,用于发送POST请求并处理响应。这两个类的结合使得在Java程序中调用HTTPS接口变得更加简单。
描述中提到的“可以通过躲避证书,绕过加密算法来获取数据”,这指的是安全漏洞或恶意攻击者可能利用的手段,如中间人攻击或者信任不当的自签名证书。 HttpClient 4.2.5在处理HTTPS连接时,提供了证书管理的灵活性...
SSL跳过证书 java ctx.init(null, new TrustManager[] { tm }, new java.security.SecureRandom()); // SSLConnectionSocketFactory ssf = new SSLConnectionSocketFactory( // ctx, NoopHostnameVerifier.INSTANCE)...
然而,在某些开发或测试环境中,可能需要绕过证书校验,例如在自签名证书的本地服务器上。Java提供了一种机制,通过自定义`SSLContext`来实现这一目的。以下是一个实例代码,展示了如何创建一个不进行证书校验的`SSL...
为了调试或测试目的,开发者可能需要绕过默认的证书验证机制,例如在使用自签名证书的服务器上。这时,可以通过创建自定义的TrustManager并设置到HttpsURLConnection中,以接受特定的证书。但这仅限于测试环境,因为...
1. 绕过证书验证实现HTTPS: ```java SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(new Scheme("https", PlainSocketFactory.getSocketFactory(), 443)); ...
对于示例代码,可能使用`NoopHostnameVerifier`来绕过SSL验证,但这在生产环境中应谨慎使用,因为它可能带来安全风险。 然后,我们可以创建`CloseableHttpClient`实例,并使用`execute(HttpUriRequest request)`...
在IT行业中,网络通信是应用程序的核心部分,而HTTP和HTTPS协议是互联网上最常用的通信...通过实践和分析这个代码,开发者可以增强自己在处理HTTP和HTTPS连接方面的能力,同时理解如何在特定情况下安全地绕过证书验证。
一个更好的解决方案是通过重写SSLContextBuilder类,强制置空KeyManagers和TrustManagers中的私有值,从而绕过Java默认的算法限制。 超时时间设置不生效是使用httpclient的另一个常见问题。开发者在设置超时参数时...