生成证书
openssl genrsa -des3 -out server.key 2048
openssl req -new -x509 -key server.key -out ca.crt -days 3650
openssl pkcs12 -export -out server.p12 -inkey server.key -in server.crt
1.继承SSLSocketFactory
/** * Author:JsonLu * DateTime:2016/5/31 19:46 * Email:[email protected] * Desc: **/ public class SecureSSLSocketFactory extends SSLSocketFactory { private final SSLContext sslContext = SSLContext.getInstance("TLS"); public SecureSSLSocketFactory(KeyStore keystore, String keystorePassword, KeyStore truststore) throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException { super(keystore, keystorePassword, truststore); try { KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); keyManagerFactory.init(keystore, keystorePassword.toCharArray()); KeyManager[] km = keyManagerFactory.getKeyManagers(); TrustManager[] tm = null; if (truststore == null) { tm = new TrustManager[] { new X509TrustManager() { @Override public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[] {}; } @Override public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException { } @Override public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException { } } }; } else { TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init(truststore); tm = trustManagerFactory.getTrustManagers(); } sslContext.init(km, tm, null); } catch (Exception e) { e.printStackTrace(); } } @Override public Socket createSocket(Socket socket, String host, int port, boolean autoClose) throws IOException, UnknownHostException { return sslContext.getSocketFactory().createSocket(socket, host, port, autoClose); } @Override public Socket createSocket() throws IOException { return sslContext.getSocketFactory().createSocket(); } }
2.
/** * Author:JsonLu * DateTime:2016/5/31 20:02 * Email:[email protected] * Desc: **/ public class SecureHttpsClient extends DefaultHttpClient { private static KeyStore keyStore,trustStore; private static String keyStorePwd; private Context ctx; private final String KEYSTORE_FILE = "client.p12"; private final String TRUESTSTORE_FILE = "server.p12"; private final String KEYSTORE_PWD = "a123456789"; private final String TRUESTSORE_PWD = "a123456"; public SecureHttpsClient(Context context){ ctx = context; init(KEYSTORE_FILE,KEYSTORE_PWD,TRUESTSTORE_FILE,TRUESTSORE_PWD); } public void init(KeyStore keyStore,KeyStore trustStore,String keyStorePwd){ this.keyStore = keyStore; this.trustStore = trustStore; this.keyStorePwd = keyStorePwd; } public void init(String keyStoreFile,String keyStorePwd,String trustStoreFile,String truestStorePwd){ this.keyStore = getKeyStoreByP12(keyStoreFile,keyStorePwd); this.trustStore = getKeyStoreByP12(trustStoreFile,truestStorePwd); this.keyStorePwd = keyStorePwd; } @Override protected ClientConnectionManager createClientConnectionManager() { try { SecureSSLSocketFactory sf = new SecureSSLSocketFactory(keyStore, keyStorePwd, trustStore); sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); HttpParams params = new BasicHttpParams(); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(params, HTTP.UTF_8); SchemeRegistry registry = new SchemeRegistry(); registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); registry.register(new Scheme("https", sf, 443)); ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry); return ccm; } catch (Exception e) { e.printStackTrace(); } return null; } public KeyStore getKeyStoreByP12(String p12File, String p12Pwd) { InputStream p12In = null; try { p12In = ctx.getResources().getAssets().open(p12File); KeyStore keyStore = KeyStore.getInstance("PKCS12"); keyStore.load(p12In, p12Pwd.toCharArray()); return keyStore; } catch (Exception e) { e.printStackTrace(); return null; } finally { try { if (p12In != null) { p12In.close(); } } catch (Exception e2) { e2.printStackTrace(); } } } }
3.
/** * Author:JsonLu * DateTime:2016/5/31 20:28 * Email:[email protected] * Desc: **/ public class CallServer { private final String HTTPS_URL = "https://192.168.8.116:8443/"; private DefaultHttpClient getSumpayHttpsClient(Context context) { SecureHttpsClient client = new SecureHttpsClient(context); client.getParams().setIntParameter(HttpConnectionParams.CONNECTION_TIMEOUT,60); client.getParams().setIntParameter(HttpConnectionParams.SO_TIMEOUT,60); return client; } public String goHttpsPost(String method,HashMap<String, String> reqParmas, Context context) { String result = null; HttpPost post = new HttpPost(HTTPS_URL + method); HttpResponse response; try { List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); Set<String> paramsKeySet = reqParmas.keySet(); Iterator<String> ite = paramsKeySet.iterator(); while (ite.hasNext()) { String key = ite.next(); nameValuePairs.add(new BasicNameValuePair(key, reqParmas .get(key))); } post.setEntity(new UrlEncodedFormEntity(nameValuePairs, "utf-8")); DefaultHttpClient httpClient = getSumpayHttpsClient(context); response = httpClient.execute(post); if (response.getStatusLine().getStatusCode() != 404) { result = EntityUtils.toString(response.getEntity(), "utf-8"); } else { } } catch (IOException e) { e.printStackTrace(); return null; } finally { post.abort(); } Log.d("https请求返回数据",result); return result; } }
4.
/** * Author:JsonLu * DateTime:2016/5/31 20:33 * Email:[email protected] * Desc: **/ public class DemoHttps extends Activity{ private CallServer callServer = new CallServer(); private TextView tv_content; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tv_content = (TextView) findViewById(R.id.content); } public void onClick(View v){ new Thread(){ @Override public void run() { HashMap hashMap = new HashMap<String,String>(); hashMap.put("data","data"); String res = callServer.goHttpsPost("https", hashMap, getBaseContext()); Message msg = new Message(); msg.obj = res; handler.sendMessage(msg); } }.start(); } Handler handler = new Handler(){ @Override public void handleMessage(Message msg) { tv_content.setText((String) msg.obj); } }; }
时间: 2024-10-14 04:47:44