midlet中使用https完全指南
网上搜索了半天,都比较凌乱,花了好几个小时才搞定,写下来备忘,同时供大家参考!
1、生成一个证书
使用jdk自带的工具keytool来生成证书,假设jdk安装路径为d:\jdk
- void?getViaHttpsConnection(String?url)? ??
- ????????????throws?CertificateException,?IOException?{ ??
- ?????????HttpsConnection?c?=?null; ??
- ?????????InputStream?is?=?null; ??
- ?????????try?{ ??
- ?????????????c?=?(HttpsConnection)Connector.open(url); ??
- ? ??
- ?????????????//?Getting?the?InputStream?ensures?that?the?connection ??
- ?????????????//?is?opened?(if?it?was?not?already?handled?by ??
- ?????????????//?Connector.open())?and?the?SSL?handshake?is?exchanged, ??
- ?????????????//?and?the?HTTP?response?headers?are?read. ??
- ?????????????//?These?are?stored?until?requested. ??
- ?????????????is?=?c.openDataInputStream(); ??
- ? ??
- ?????????????if?c.getResponseCode()?==?HttpConnection.HTTP_OK)?{ ??
- ?????????????????//?Get?the?length?and?process?the?data ??
- ?????????????????int?len?=?(int)c.getLength(); ??
- ?????????????????if?(len?>?0)?{ ??
- ?????????????????????byte[]?data?=?new?byte[len]; ??
- ?????????????????????int?actual?=?is.readFully(data); ??
- ?????????????????????... ??
- ?????????????????}?else?{ ??
- ?????????????????????int?ch; ??
- ?????????????????????while?((ch?=?is.read())?!=?-1)?{ ??
- ?????????????????????????... ??
- ?????????????????????} ??
- ?????????????????} ??
- ?????????????}?else?{ ??
- ???????????????... ??
- ?????????????} ??
- ?????????}?finally?{ ??
- ?????????????if?(is?!=?null) ??
- ?????????????????is.close(); ??
- ?????????????if?(c?!=?null) ??
- ?????????????????c.close(); ??
- ?????????} ??
- ?????} ??
?编写完成后,用模拟器应该就可以访问https了。
?
5、可能遇到的问题
1)运行midlet时,异常Certificate ? was ? issued ? by ? an ? unrecognized ? entity??
未将证书导入到wtk中
2)使用wtk界面来导入证书的时候,提示too big
换成文中描述的命令行方式来导入或者使用keytool导出一个cert证书
3)Certificate does not contain the correct site name
keystore里面的CN值不正确,重新生成keystore,CN填写为主机名,比如 127.0.0.1
4)删除证书
keytool? -delete -alias tomcat -keystore c:\keystore -storepass hxrainbow
?
?
1 楼 redduke1202 2007-12-07 MIDlet开发,就要以部署到手机上为目标.而不是仅仅在模拟器上运行就好了1.手机上貌似导入证书还比较麻烦
2.https依赖于长连接,而目前中移动的网络环境下,不存在长连接,无法使用https 2 楼 wuhua 2008-01-21 redduke1202 写道MIDlet开发,就要以部署到手机上为目标.而不是仅仅在模拟器上运行就好了
1.手机上貌似导入证书还比较麻烦
2.https依赖于长连接,而目前中移动的网络环境下,不存在长连接,无法使用https
证书的安装还是不麻烦的。