当前位置:   article > 正文

Android支持https的处理方式2----HttpURLConnection请求https处理方式_android httpurlconnection ssl

android httpurlconnection ssl

接着上一篇,这次讲解HttpURLConnection请求https处理方式,过程其实差不多,具体的有一点区别。

1、单向验证证书的https请求

首先获取SSLContext的对象,这是为了获取SSLSocketFactory的对象。

  1. /**
  2. * 获取Https的证书
  3. * @param context Activity(fragment)的上下文
  4. * @return SSL的上下文对象
  5. */
  6. private static SSLContext getSSLContext(Context context) {
  7. SSLContext s_sSLContext = null;
  8. if (null != s_sSLContext) {
  9. return s_sSLContext;
  10. }
  11. CertificateFactory certificateFactory = null;
  12. InputStream inputStream = null;
  13. KeyStore keystore = null;
  14. String tmfAlgorithm = null;
  15. TrustManagerFactory trustManagerFactory = null;
  16. try {
  17. certificateFactory = CertificateFactory.getInstance("X.509");
  18. inputStream = context.getAssets().open("user.crt");//这里导入SSL证书文件
  19. // inputStream = context.getAssets().open("51p2b_server_bs.pem");//这里导入SSL证书文件
  20. Certificate ca = certificateFactory.generateCertificate(inputStream);
  21. keystore = KeyStore.getInstance(KeyStore.getDefaultType());
  22. keystore.load(null, null);
  23. keystore.setCertificateEntry("ca", ca);
  24. tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
  25. trustManagerFactory = TrustManagerFactory.getInstance(tmfAlgorithm);
  26. trustManagerFactory.init(keystore);
  27. // Create an SSLContext that uses our TrustManager
  28. s_sSLContext = SSLContext.getInstance("TLS");
  29. s_sSLContext.init(null, trustManagerFactory.getTrustManagers(), null);
  30. return s_sSLContext;
  31. } catch (CertificateException e) {
  32. e.printStackTrace();
  33. } catch (KeyManagementException e) {
  34. e.printStackTrace();
  35. } catch (NoSuchAlgorithmException e) {
  36. e.printStackTrace();
  37. } catch (KeyStoreException e) {
  38. e.printStackTrace();
  39. } catch (IOException e) {
  40. e.printStackTrace();
  41. }
  42. return null;
  43. }


接下来就是验证证书和请求的操作了

  1. public String httpGet(String httpUrl) {
  2. BufferedReader input = null;
  3. StringBuilder sb = null;
  4. URL url = null;
  5. HttpURLConnection con = null;
  6. try {
  7. url = new URL(httpUrl);
  8. try {
  9. SSLContext sslContext = getSSLContext(activity);
  10. HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
  11. HttpsURLConnection https= (HttpsURLConnection) url.openConnection();
  12. HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
  13. @Override
  14. public boolean verify(String hostname, SSLSession sslsession) {
  15. if("host".equals(hostname)){//判断域名是否和证书域名相等
  16. return true;
  17. } else {
  18. return false;
  19. }
  20. }});
  21. if (url.getProtocol().toLowerCase().equals("https")) {//判断是http还是https
  22. //https.setHostnameVerifier(DO_NOT_VERIFY);
  23. con = https;
  24. } else {
  25. con = (HttpURLConnection)url.openConnection();
  26. }
  27. input = new BufferedReader(new InputStreamReader(con.getInputStream()));
  28. sb = new StringBuilder();
  29. String s;
  30. while ((s = input.readLine()) != null) {
  31. sb.append(s).append("\n");
  32. }
  33. } catch (IOException e) {
  34. e.printStackTrace();
  35. }
  36. } catch (MalformedURLException e1) {
  37. e1.printStackTrace();
  38. } finally {
  39. // close buffered
  40. if (input != null) {
  41. try {
  42. input.close();
  43. } catch (IOException e) {
  44. e.printStackTrace();
  45. }
  46. }
  47. // disconnecting releases the resources held by a connection so they may be closed or reused
  48. if (con != null) {
  49. con.disconnect();
  50. }
  51. }
  52. return sb == null ? null : sb.toString();
  53. }

2、信任所有证书的处理方式

  1. /**
  2. * 信任所有服务器,无需验证证书
  3. */
  4. private static void trustAllHosts() {
  5. final String TAG = "trustAllHosts";
  6. // Create a trust manager that does not validate certificate chains
  7. TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
  8. public java.security.cert.X509Certificate[] getAcceptedIssuers() {
  9. return new java.security.cert.X509Certificate[] {};
  10. }
  11. public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
  12. }
  13. public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
  14. }
  15. } };
  16. // Install the all-trusting trust manager
  17. try {
  18. SSLContext sc = SSLContext.getInstance("TLS");
  19. sc.init(null, trustAllCerts, new java.security.SecureRandom());
  20. HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
  21. } catch (Exception e) {
  22. e.printStackTrace();
  23. }
  24. }


  1. public String httpGet(String httpUrl) {
  2. BufferedReader input = null;
  3. StringBuilder sb = null;
  4. URL url = null;
  5. HttpURLConnection con = null;
  6. try {
  7. url = new URL(httpUrl);
  8. try {
  9. // trust all hosts
  10. trustAllHosts();
  11. HttpsURLConnection https= (HttpsURLConnection) url.openConnection();
  12. HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
  13. @Override
  14. public boolean verify(String hostname, SSLSession sslsession) {
  15. if("host".equals(hostname)){
  16. return true;
  17. } else {
  18. return false;
  19. }
  20. }});
  21. if (url.getProtocol().toLowerCase().equals("https")) {
  22. https.setHostnameVerifier(DO_NOT_VERIFY);
  23. con = https;
  24. } else {
  25. con = (HttpURLConnection)url.openConnection();
  26. }
  27. input = new BufferedReader(new InputStreamReader(con.getInputStream()));
  28. sb = new StringBuilder();
  29. String s;
  30. while ((s = input.readLine()) != null) {
  31. sb.append(s).append("\n");
  32. }
  33. } catch (IOException e) {
  34. e.printStackTrace();
  35. }
  36. } catch (MalformedURLException e1) {
  37. e1.printStackTrace();
  38. } finally {
  39. // close buffered
  40. if (input != null) {
  41. try {
  42. input.close();
  43. } catch (IOException e) {
  44. e.printStackTrace();
  45. }
  46. }
  47. // disconnecting releases the resources held by a connection so they may be closed or reused
  48. if (con != null) {
  49. con.disconnect();
  50. }
  51. }
  52. return sb == null ? null : sb.toString();
  53. }
  54. final static HostnameVerifier DO_NOT_VERIFY = new HostnameVerifier() {
  55. public boolean verify(String hostname, SSLSession session) {
  56. return true;
  57. }
  58. };

这样就不必验证证书了。

3、双向验证证书的操作

  1. public class HttpsPost {
  2. /**
  3. * 获得KeyStore.
  4. * @param keyStorePath
  5. * 密钥库路径
  6. * @param password
  7. * 密码
  8. * @return 密钥库
  9. * @throws Exception
  10. */
  11. public static KeyStore getKeyStore(String password, String keyStorePath)
  12. throws Exception {
  13. // 实例化密钥库
  14. KeyStore ks = KeyStore.getInstance("JKS");
  15. // 获得密钥库文件流
  16. FileInputStream is = new FileInputStream(keyStorePath);
  17. // 加载密钥库
  18. ks.load(is, password.toCharArray());
  19. // 关闭密钥库文件流
  20. is.close();
  21. return ks;
  22. }
  23. /**
  24. * 获得SSLSocketFactory.
  25. * @param password
  26. * 密码
  27. * @param keyStorePath
  28. * 密钥库路径
  29. * @param trustStorePath
  30. * 信任库路径
  31. * @return SSLSocketFactory
  32. * @throws Exception
  33. */
  34. public static SSLContext getSSLContext(String password,
  35. String keyStorePath, String trustStorePath) throws Exception {
  36. // 实例化密钥库
  37. KeyManagerFactory keyManagerFactory = KeyManagerFactory
  38. .getInstance(KeyManagerFactory.getDefaultAlgorithm());
  39. // 获得密钥库
  40. KeyStore keyStore = getKeyStore(password, keyStorePath);
  41. // 初始化密钥工厂
  42. keyManagerFactory.init(keyStore, password.toCharArray());
  43. // 实例化信任库
  44. TrustManagerFactory trustManagerFactory = TrustManagerFactory
  45. .getInstance(TrustManagerFactory.getDefaultAlgorithm());
  46. // 获得信任库
  47. KeyStore trustStore = getKeyStore(password, trustStorePath);
  48. // 初始化信任库
  49. trustManagerFactory.init(trustStore);
  50. // 实例化SSL上下文
  51. SSLContext ctx = SSLContext.getInstance("TLS");
  52. // 初始化SSL上下文
  53. ctx.init(keyManagerFactory.getKeyManagers(),
  54. trustManagerFactory.getTrustManagers(), null);
  55. // 获得SSLSocketFactory
  56. return ctx;
  57. }
  58. /**
  59. * 初始化HttpsURLConnection.
  60. * @param password
  61. * 密码
  62. * @param keyStorePath
  63. * 密钥库路径
  64. * @param trustStorePath
  65. * 信任库路径
  66. * @throws Exception
  67. */
  68. public static void initHttpsURLConnection(String password,
  69. String keyStorePath, String trustStorePath) throws Exception {
  70. // 声明SSL上下文
  71. SSLContext sslContext = null;
  72. // 实例化主机名验证接口
  73. HostnameVerifier hnv = new MyHostnameVerifier();
  74. try {
  75. sslContext = getSSLContext(password, keyStorePath, trustStorePath);
  76. } catch (GeneralSecurityException e) {
  77. e.printStackTrace();
  78. }
  79. if (sslContext != null) {
  80. HttpsURLConnection.setDefaultSSLSocketFactory(sslContext
  81. .getSocketFactory());
  82. }
  83. HttpsURLConnection.setDefaultHostnameVerifier(hnv);
  84. }
  85. /**
  86. * 发送请求.
  87. * @param httpsUrl
  88. * 请求的地址
  89. * @param xmlStr
  90. * 请求的数据
  91. */
  92. public static void post(String httpsUrl, String xmlStr) {
  93. HttpsURLConnection urlCon = null;
  94. try {
  95. urlCon = (HttpsURLConnection) (new URL(httpsUrl)).openConnection();
  96. urlCon.setDoInput(true);
  97. urlCon.setDoOutput(true);
  98. urlCon.setRequestMethod("POST");
  99. urlCon.setRequestProperty("Content-Length",
  100. String.valueOf(xmlStr.getBytes().length));
  101. urlCon.setUseCaches(false);
  102. //设置为gbk可以解决服务器接收时读取的数据中文乱码问题
  103. urlCon.getOutputStream().write(xmlStr.getBytes("gbk"));
  104. urlCon.getOutputStream().flush();
  105. urlCon.getOutputStream().close();
  106. BufferedReader in = new BufferedReader(new InputStreamReader(
  107. urlCon.getInputStream()));
  108. String line;
  109. while ((line = in.readLine()) != null) {
  110. System.out.println(line);
  111. }
  112. } catch (MalformedURLException e) {
  113. e.printStackTrace();
  114. } catch (IOException e) {
  115. e.printStackTrace();
  116. } catch (Exception e) {
  117. e.printStackTrace();
  118. }
  119. }
  120. /**
  121. * 测试方法.
  122. * @param args
  123. * @throws Exception
  124. */
  125. public static void main(String[] args) throws Exception {
  126. // 密码
  127. String password = "123456";
  128. // 密钥库
  129. String keyStorePath = "tomcat.keystore";
  130. // 信任库
  131. String trustStorePath = "tomcat.keystore";
  132. // 本地起的https服务
  133. String httpsUrl = "https://localhost:8443/service/httpsPost";
  134. // 传输文本
  135. String xmlStr = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><fruitShop><fruits><fruit><kind>萝卜</kind></fruit><fruit><kind>菠萝</kind></fruit></fruits></fruitShop>";
  136. HttpsPost.initHttpsURLConnection(password, keyStorePath, trustStorePath);
  137. // 发起请求
  138. HttpsPost.post(httpsUrl, xmlStr);
  139. }
  140. }public class HttpsPost {
  141. /**
  142. * 获得KeyStore.
  143. * @param keyStorePath
  144. * 密钥库路径
  145. * @param password
  146. * 密码
  147. * @return 密钥库
  148. * @throws Exception
  149. */
  150. public static KeyStore getKeyStore(String password, String keyStorePath)
  151. throws Exception {
  152. // 实例化密钥库
  153. KeyStore ks = KeyStore.getInstance("JKS");
  154. // 获得密钥库文件流
  155. FileInputStream is = new FileInputStream(keyStorePath);
  156. // 加载密钥库
  157. ks.load(is, password.toCharArray());
  158. // 关闭密钥库文件流
  159. is.close();
  160. return ks;
  161. }
  162. /**
  163. * 获得SSLSocketFactory.
  164. * @param password
  165. * 密码
  166. * @param keyStorePath
  167. * 密钥库路径
  168. * @param trustStorePath
  169. * 信任库路径
  170. * @return SSLSocketFactory
  171. * @throws Exception
  172. */
  173. public static SSLContext getSSLContext(String password,
  174. String keyStorePath, String trustStorePath) throws Exception {
  175. // 实例化密钥库
  176. KeyManagerFactory keyManagerFactory = KeyManagerFactory
  177. .getInstance(KeyManagerFactory.getDefaultAlgorithm());
  178. // 获得密钥库
  179. KeyStore keyStore = getKeyStore(password, keyStorePath);
  180. // 初始化密钥工厂
  181. keyManagerFactory.init(keyStore, password.toCharArray());
  182. // 实例化信任库
  183. TrustManagerFactory trustManagerFactory = TrustManagerFactory
  184. .getInstance(TrustManagerFactory.getDefaultAlgorithm());
  185. // 获得信任库
  186. KeyStore trustStore = getKeyStore(password, trustStorePath);
  187. // 初始化信任库
  188. trustManagerFactory.init(trustStore);
  189. // 实例化SSL上下文
  190. SSLContext ctx = SSLContext.getInstance("TLS");
  191. // 初始化SSL上下文
  192. ctx.init(keyManagerFactory.getKeyManagers(),
  193. trustManagerFactory.getTrustManagers(), null);
  194. // 获得SSLSocketFactory
  195. return ctx;
  196. }
  197. /**
  198. * 初始化HttpsURLConnection.
  199. * @param password
  200. * 密码
  201. * @param keyStorePath
  202. * 密钥库路径
  203. * @param trustStorePath
  204. * 信任库路径
  205. * @throws Exception
  206. */
  207. public static void initHttpsURLConnection(String password,
  208. String keyStorePath, String trustStorePath) throws Exception {
  209. // 声明SSL上下文
  210. SSLContext sslContext = null;
  211. // 实例化主机名验证接口
  212. HostnameVerifier hnv = new MyHostnameVerifier();
  213. try {
  214. sslContext = getSSLContext(password, keyStorePath, trustStorePath);
  215. } catch (GeneralSecurityException e) {
  216. e.printStackTrace();
  217. }
  218. if (sslContext != null) {
  219. HttpsURLConnection.setDefaultSSLSocketFactory(sslContext
  220. .getSocketFactory());
  221. }
  222. HttpsURLConnection.setDefaultHostnameVerifier(hnv);
  223. }
  224. /**
  225. * 发送请求.
  226. * @param httpsUrl
  227. * 请求的地址
  228. * @param xmlStr
  229. * 请求的数据
  230. */
  231. public static void post(String httpsUrl, String xmlStr) {
  232. HttpsURLConnection urlCon = null;
  233. try {
  234. urlCon = (HttpsURLConnection) (new URL(httpsUrl)).openConnection();
  235. urlCon.setDoInput(true);
  236. urlCon.setDoOutput(true);
  237. urlCon.setRequestMethod("POST");
  238. urlCon.setRequestProperty("Content-Length",
  239. String.valueOf(xmlStr.getBytes().length));
  240. urlCon.setUseCaches(false);
  241. //设置为gbk可以解决服务器接收时读取的数据中文乱码问题
  242. urlCon.getOutputStream().write(xmlStr.getBytes("gbk"));
  243. urlCon.getOutputStream().flush();
  244. urlCon.getOutputStream().close();
  245. BufferedReader in = new BufferedReader(new InputStreamReader(
  246. urlCon.getInputStream()));
  247. String line;
  248. while ((line = in.readLine()) != null) {
  249. System.out.println(line);
  250. }
  251. } catch (MalformedURLException e) {
  252. e.printStackTrace();
  253. } catch (IOException e) {
  254. e.printStackTrace();
  255. } catch (Exception e) {
  256. e.printStackTrace();
  257. }
  258. }
  259. /**
  260. * 测试方法.
  261. * @param args
  262. * @throws Exception
  263. */
  264. public static void main(String[] args) throws Exception {
  265. // 密码
  266. String password = "123456";
  267. // 密钥库
  268. String keyStorePath = "tomcat.keystore";
  269. // 信任库
  270. String trustStorePath = "tomcat.keystore";
  271. // 本地起的https服务
  272. String httpsUrl = "https://localhost:8443/service/httpsPost";
  273. // 传输文本
  274. String xmlStr = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><fruitShop><fruits><fruit><kind>萝卜</kind></fruit><fruit><kind>菠萝</kind></fruit></fruits></fruitShop>";
  275. HttpsPost.initHttpsURLConnection(password, keyStorePath, trustStorePath);
  276. // 发起请求
  277. HttpsPost.post(httpsUrl, xmlStr);
  278. }
  279. }


4、如果你用的xutils3的框架, params.setSslSocketFactory(sslContext.getSocketFactory());这个方法认证证书

声明:本文内容由网友自发贡献,转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号