源自:http://www.javaeye.com/topic/146494)
网上搜索了半天,都比较凌乱,花了好几个小时才搞定,写下来备忘,同时供大家参考!
1、生成一个证书
使用jdk自带的工具keytool来生成证书,假设jdk安装路径为d:/jdk
- cd D:/jdk/bin
- keytool -genkey -alias tomcat -keyalg RSA -keystore c:/keystore
按照提示回答问题,完了后在c盘根目录下就生成了证书文件keystore. 注意填写您的姓名的时候要填写网站的主机名,比如localhost。
2、在tomcat5中配置https
将server.xml中找到下面的代码,默认被注释掉了
- <Connector port="8443" maxHttpHeaderSize="8192"
- maxThreads="150" minSpareThreads="25" maxSpareThreads="75"
- enableLookups="false" disableUploadTimeout="true"
- acceptCount="100" scheme="https" secure="true"
- clientAuth="false" sslProtocol="TLS" />
替换为
- <Connector port="443" maxHttpHeaderSize="8192"
- maxThreads="150" minSpareThreads="25" maxSpareThreads="75"
- enableLookups="true" disableUploadTimeout="true"
- acceptCount="100" scheme="https" secure="true"
- clientAuth="false" sslProtocol="TLS" keystoreFile="c:/keystore"
- keystorePass="hxrainbow"/>
重新启动tomcat,使用https应该就能访问到了。
3、导入证书到wtk
假设wtk的安装路径为D:/WTK2.5.2/
- cd D:/WTK2.5.2/bin
- mekeytool.exe -import -keystore c:/keystore -storepass hxrainbow -alias tomcat
没有错误提示,就导入成功。
4、在midlet中使用https
主要就是使用HttpsConnection,HttpsConnection是HttpConnection的子类,使用方法一样的,不再啰嗦了,给个帮助手册里面的代码
- 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