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/
謝謝您的贊助,我會做的更好!