androd中使用 https ssl
16lz
2021-01-25
android平台上支持的keystore type好像只有PKCS12,不支持JKS。
使用https的前提是,服务器必须首先配置好ssl,配置安全连接各种服务器都有说明文档,在此不多说了、
还必须把服务器证书导出来,通过浏览器就可以导出来,此处导出的证书文件为: my.cer
可以把证书放在asset文件夹下,或者放到raw文件加下,以流的形式读出来。
下面是在android上的代码,经过测试,没有任何问题
public class HttpsActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); try { https();} catch (KeyManagementException e) {Log.e("https", e.getMessage());} catch (ClientProtocolException e) {Log.e("https", e.getMessage());} catch (KeyStoreException e) {Log.e("https", e.getMessage());} catch (NoSuchAlgorithmException e) {Log.e("https", e.getMessage());} catch (CertificateException e) {Log.e("https", e.getMessage());} catch (UnrecoverableKeyException e) {Log.e("https", e.getMessage());} catch (IOException e) {Log.e("https", e.getMessage());} } public void https() throws ClientProtocolException, IOException, KeyStoreException, NoSuchAlgorithmException, CertificateException, KeyManagementException, UnrecoverableKeyException{ DefaultHttpClient httpclient = new DefaultHttpClient(); try { KeyStore trustStore = KeyStore.getInstance("PKCS12"); InputStream instream = getResources().openRawResource(R.raw.my); CertificateFactory cerFactory = CertificateFactory.getInstance("X.509"); java.security.cert.Certificate cer = cerFactory.generateCertificate(instream); try { trustStore.load(null, null); trustStore.setCertificateEntry("trust", cer); } finally { try { instream.close(); } catch (Exception ignore) {} } SSLSocketFactory socketFactory = new SSLSocketFactory(trustStore); Scheme https = new Scheme("https", socketFactory, 8443); httpclient.getConnectionManager().getSchemeRegistry().register(https); HttpGet httpget = new HttpGet("https://服务器IP:8443/httpsServer/httpstest?username=mmmm&password=pppp"); System.out.println("executing request" + httpget.getRequestLine()); Log.i("https", "executing request" + httpget.getRequestLine()); HttpResponse response = httpclient.execute(httpget); HttpEntity entity = response.getEntity(); Log.i("https", "----------------------------------------"); System.out.println(response.getStatusLine()); if (entity != null) { Log.i("https", "Response content length: " + entity.getContentLength()); } } finally { // When HttpClient instance is no longer needed, // shut down the connection manager to ensure // immediate deallocation of all system resources httpclient.getConnectionManager().shutdown(); } } }如果有什么地方不妥的地方,请指正,不胜感激。
更多相关文章
- 万字长文带你了解最常用的开源 Squid 代理服务器
- 一款常用的 Squid 日志分析工具
- Nginx系列教程(一)| 手把手教你在Linux环境下搭建Nginx服务
- GitHub 标星 8K+!一款开源替代 ls 的工具你值得拥有!
- Nginx系列教程(三)| 一文带你读懂Nginx的负载均衡
- RHEL 6 下 DHCP+TFTP+FTP+PXE+Kickstart 实现无人值守安装
- Linux 环境下实战 Rsync 备份工具及配置 rsync+inotify 实时同步
- Android(安卓)资源和国际化 [复制链接]
- Zxing图片拉伸解决 Android(安卓)二维码扫描