HTTPS Full web Development
Tomcat 6.0 Configuration
1. Generate a secure access certificate.
Command line execution: Keytool-genkey-alias tomcat-keyalg rsa-keystore C:\tomcat.keystore
Then follow the prompts to enter some information such as passwords:
Enter KeyStore Password:
Enter the new password again:
What is your first and last name?
[Unknown]: Tomcat
What is the name of your organizational unit?
[Unknown]: Tomcat
What is your organization's name?
[Unknown]: Tomcat
What is the name of your city or region?
[Unknown]: BJ
What is the name of your state or province?
[Unknown]: BJ
What is the two-letter country code for this unit?
[Unknown]: CN
Cn=tomcat, Ou=tomcat, O=tomcat, L=BJ, ST=BJ, C=CN right?
[No]: Y
Enter the master password for <tomcat>
(If the KeyStore password is the same, press ENTER):
After the input is completed, the Tomcat.keystore file is generated under the C drive, and the location of this file is not required.
Note: The blue part of the above command may not be entered, so a. KeyStore certificate file is generated by default.
2. Configure Tomcat so that it supports HTTPS connections.
Open the Conf/server.xml file under the Tomcat directory, and note the previous Connection section to find the following node:
<!--Define a SSL http/1.1 Connector on port 8443 This Connector uses the JSSE configuration, when using APR, the
connector should be using the "OpenSSL" style configuration described in the APR documentation- <!--
<connector port= "8443" protocol= "http/1.1" sslenabled= "true" maxthreads= "" scheme= "https" secure= "true" clientauth= "false" sslprotocol= "TLS"/>--
Remove the comments from the <connectore node and change the 8443 to the port you want to use. Add two properties to a node: keystorefile= "C:/tomcat.keystore" keystorepass= "123456"
Where keystorefile refers to the certificate file location you generated in the first step, and Keystorepass is the password you entered when you generated the certificate.
With these two steps, you can basically use HTTPS to access the Tomcat connection, but when I use the TOMCAT6 configuration, I start Tomcat error:
2011-9-8 10:11:20 org.apache.catalina.core.AprLifecycleListener init info: Loaded APR based Apache Tomcat Native Library 1.1 .20. 2011-9-8 10:11:20 org.apache.catalina.core.AprLifecycleListener init info: APR Capabilities:ipv6 [true], sendfile [true], Accept filters [FALSE], random [true]. 2011-9-8 10:11:20 org.apache.catalina.startup.SetAllPropertiesRule begin WARNING: [setallpropertiesrule]{server/service/ Connector} Setting Property ' Keystorefile ' to ' C:\tomcat.keystore ' didn't not find a matching property. 2011-9-8 10:11:20 org.apache.catalina.startup.SetAllPropertiesRule begin WARNING: [setallpropertiesrule]{server/service/ Connector} Setting Property ' Keystorepass ' to ' Mvtech ' didn't not find a matching property. 2011-9-8 10:11:20 org.apache.catalina.startup.SetAllPropertiesRule begin WARNING: [setallpropertiesrule]{server/service/ Connector} Setting Property ' ClientAuth ' to ' false ' does not ' is ' find a matching property. 2011-9-8 10:11:20 org.apache.coyote.http11.Http11AprProtocol init critical: Error initializing endPoint java.lang.Exception:No Certificate file specified or invalid file format at Org.apache.tomcat.jni.SSLContext.setCe Rtificate (Native Method) at Org.apache.tomcat.util.net.AprEndpoint.init (aprendpoint.java:720) at Org.apache.coyote.http11.Http11AprProtocol.init (http11aprprotocol.java:107) at Org.apache.catalina.connector.Connector.initialize (connector.java:1014) at Org.apache.catalina.core.StandardService.initialize (standardservice.java:680) at Org.apache.catalina.core.StandardServer.initialize (standardserver.java:795) at Org.apache.catalina.startup.Catalina.load (catalina.java:524) at Org.apache.catalina.startup.Catalina.load ( catalina.java:548) at Sun.reflect.NativeMethodAccessorImpl.invoke0 (Native Method) at Sun.reflect.NativeMethodAccessorImpl.invoke (nativemethodaccessorimpl.java:39) at Sun.reflect.DelegatingMethodAccessorImpl.invoke (DELEGATINGMETHODACCESSORIMPL.JAVA:25) at Java.lang.reflect.Method.invoke (method.java:597) at Org.apache.catalina.startup.Bootstrap.load(bootstrap.java:261) at Org.apache.catalina.startup.Bootstrap.main (bootstrap.java:413) 2011-9-8 10:11:20 Org.apache.catalina.startup.Catalina load severity: Catalina.start Lifecycleexception:protocol Handler Initialization Failed:java.lang.Exception:No Certificate file specified or invalid file format at Org.apache.catalina.connector.Connec Tor.initialize (connector.java:1016) at Org.apache.catalina.core.StandardService.initialize (Standardservice.java : 680) at Org.apache.catalina.core.StandardServer.initialize (standardserver.java:795) at Org.apache.catalina.startup.Catalina.load (catalina.java:524) at Org.apache.catalina.startup.Catalina.load ( catalina.java:548) at Sun.reflect.NativeMethodAccessorImpl.invoke0 (Native Method) at Sun.reflect.NativeMethodAccessorImpl.invoke (nativemethodaccessorimpl.java:39) at Sun.reflect.DelegatingMethodAccessorImpl.invoke (DELEGATINGMETHODACCESSORIMPL.JAVA:25) at Java.lang.reflect.Method.invoke (method.java:597) at Org.apache.catalina.startup.Bootstrap. Load (bootstrap.java:261) at Org.apache.catalina.startup.Bootstrap.main (bootstrap.java:413)
See a friend's solution on the web, is to find a Tcnative-1.dll file in the bin directory of Tomcat, then remove it and restart Tomcat everything is OK.
At this point, you can access your app over HTTPS.
But at this point if you use HTTP to access the application, the page will return garbled or empty, but also do not error, in order to better use, we need to be able to automatically jump to HTTPS when the customer input HTTP, which requires a third step, so that your app is forced to use HTTPS access.
Open the Conf/web.xml file under Tomcat and add it after the bottom <welcome-file-list> node:
<login-config> <!--Authorization setting for SSL-to- <auth-method>client-cert</ auth-method> <realm-name>client Cert users-only area</realm-name> </login-config> <security-constraint> <!--Authorization setting for SSL-to- <web-resource-collection > <web-resource-name >SSL</web-resource-name> <url-pattern>/*</url-pattern> </web-resource-collection> <user-data-constraint> <transport-guarantee> confidential</transport-guarantee> </user-data-constraint> </security-constraint>
Configuration complete ...
Source parsing service Side
Service-side construction is relatively simple, an action is done
Package Com.httpsdemo.action;import Java.io.bufferedreader;import Java.io.ioexception;import java.io.InputStream; Import Java.io.inputstreamreader;import Javax.servlet.servletexception;import Javax.servlet.http.HttpServlet; Import Javax.servlet.http.httpservletrequest;import Javax.servlet.http.httpservletresponse;public class Posthttpsaction extends HttpServlet {/** * */private static final long serialversionuid = 1L; @Overrideprotected void D Opost (httpservletrequest req, HttpServletResponse resp) throws Servletexception, IOException {System.out.println (" Post success ... "); InputStream in = Req.getinputstream (); BufferedReader br = new BufferedReader (new InputStreamReader (in)); String result = Br.readline (); SYSTEM.OUT.PRINTLN (result); Resp.getoutputstream (). Write (Result.getbytes ("Utf-8"); return;}}
Note the Web. XML configuration.
Client
Tool class one done.
&NBSP;
Package com.saygou.weixin; Import Java.io.bytearrayoutputstream;import Java.io.dataoutputstream;import Java.io.ioexception;import Java.io.inputstream;import Java.net.url;import Java.security.keymanagementexception;import Java.security.nosuchalgorithmexception;import Java.security.cert.certificateexception;import Java.security.cert.X509Certificate; Import Javax.net.ssl.hostnameverifier;import Javax.net.ssl.httpsurlconnection;import javax.net.ssl.SSLContext; Import Javax.net.ssl.sslsession;import Javax.net.ssl.trustmanager;import Javax.net.ssl.X509TrustManager; public class Httpsutil {private static class Trustanytrustmanager implements X509trustmanager {public void C Heckclienttrusted (x509certificate[] chain, String authtype) throws Certificateexception {} public void checkservertrusted (x509certificate[] chain, String authtype) throws Certificateexception { } public x509certificate[] Getacceptedissuers () { return new x509certificate[] {}; }} private static class Trustanyhostnameverifier implements Hostnameverifier {public boolean verify (String Hostname, SSLsession session) {return true; }}/** * Post mode Request server (HTTPS protocol) * * @param URL * Request Address * @param content * Parameter * @param charset * code * @return * @throws nosuchalgorithmexception * @throws Keymana Gementexception * @throws IOException */public static byte[] Post (string URL, string content, String charset) Throws NoSuchAlgorithmException, Exception, IOException {sslcontext sc = Sslcontext.getinsta NCE ("SSL", "Sunjsse"); Sc.init (NULL, new trustmanager[] {new Trustanytrustmanager ()}, New Java.security.SecureRandom ()); URL console = new URL (URL); Httpsurlconnection conn = (httpsurlconnection) console.openconnection (); Conn.setsslsockeTfactory (Sc.getsocketfactory ()); Set default certificate-if not, error message ↓↓↓//java.io.ioexception:https hostname wrong:should BE <127.0.0.1> conn . Sethostnameverifier (New Trustanyhostnameverifier ()); Conn.setdooutput (TRUE); Conn.connect (); DataOutputStream out = new DataOutputStream (Conn.getoutputstream ()); Out.write (Content.getbytes (charset)); Refresh, close Out.flush (); Out.close (); InputStream is = Conn.getinputstream (); if (is = null) {Bytearrayoutputstream OutStream = new Bytearrayoutputstream (); byte[] buffer = new byte[1024]; int len = 0; while (len = is.read (buffer))! =-1) {outstream.write (buffer, 0, Len); } is.close (); return Outstream.tobytearray (); } return null; /** * Test * @param args * @throws Exception */public static void main (string[] args) throws Except Ion { try {byte[] b = httpsutil.post ("Https://127.0.0.1:8443/httpsDemo/hs", "{' Name ': ' Jack '}", "Utf-8"); System.out.println (New String (b));} catch (Keymanagementexception e) {//TODO auto-generated catch Blocke.printstacktrace ();} catch ( NoSuchAlgorithmException e) {//Todo auto-generated catch Blocke.printstacktrace ();} catch (IOException e) {//Todo auto-g Enerated catch Blocke.printstacktrace ();}}}
HTTPS client sends request (II)