Click here to Skip to main content
15,885,985 members
Articles / Programming Languages / Java / Java SE / J2EE
Tip/Trick

Create a Simple Web Server in Java (2) - HTTPS Server

Rate me:
Please Sign up or sign in to vote.
4.60/5 (4 votes)
24 Oct 2015CPOL2 min read 50.1K   1.6K   5   5
Create a simple and flexible HTTPS server using JDK to process GET/POST requests

Introduction

In my last tip, I introduce how to create a simple HTTP server and it is available here. The simple server is flexible enough to incorporate into your own projects.

This tip will expand the idea and create a simple HTTPS server.

Background

HTTPS (Secure Hypertext Transfer Protocol) is a secured protocol and generally used to ensure safe communication over the Internet. HTTPS uses digital certificate including a pair of private key and public key to verify the sender and receiver. The sender encrypts the information with public key and sends the data, then the receiver gets the information through decrypting the data with private key and vice versa.

Image 1

Using the Code

Since Java 1.6, there's a built-in HTTP/HTTPS server included with the J2EE SDK. The library can be downloaded here.

Steps

  • Prepare certificate
  • Load certificate
  • Start server
  • Test

1. Prepare Certificate

In Java, we can use keytool (installed with JDK) to generate certificate. keytool is a Java digital certificate management tool. Basically, keytool stores two pieces of information: the private key and certificate into a single keystore file. keytool can be used to generate a local Server Certificate - the certificate is valid but it is not identified CA (Certificate Authority) because it is only self-signed. There are more details regarding how to use this tool to create certificate here.

For example:

Open command line (Terminal), enter:

keytool -genkey -alias alias -keypass mypassword -keystore mykey.keystore -storepass mypassword
  • -genkey: required parameter
  • -alias: specify an alias name
  • -keypass: specify the password of private key
  • -keystore: specify the key file name
  • -storepass: specify the password of key

Follow the steps to enter some certification information as below, enter “y” at the end.

Image 2

A file mykey.keystore will be created in the current folder. It is the certificate.

Actually, in real project, we apply certificate from CA issuer. Here is a list.

2. Load Certificate

Now, we can do programming to load the certificate:

Java
// load certificate
String keystoreFilename = getPath() + "mycert.keystore";
char[] storepass = "mypassword".toCharArray();
char[] keypass = "mypassword".toCharArray();
String alias = "alias";
FileInputStream fIn = new FileInputStream(keystoreFilename);
KeyStore keystore = KeyStore.getInstance("JKS");
keystore.load(fIn, storepass);
// display certificate
Certificate cert = keystore.getCertificate(alias);
System.out.println(cert);
// setup the key manager factory
KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
kmf.init(keystore, keypass);
// setup the trust manager factory
TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
tmf.init(keystore);

3. Start Server

We need to create a HttpsServer object and initialize it with https context binding to the certificate:

Java
// create https server
server = HttpsServer.create(new InetSocketAddress(port), 0);
// create ssl context
SSLContext sslContext = SSLContext.getInstance(protocol);
// setup the HTTPS context and parameters
sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
server.setHttpsConfigurator(new HttpsConfigurator(sslContext) {
         public void configure(HttpsParameters params) {
                 try {
                          // initialise the SSL context
                          SSLContext c = SSLContext.getDefault();
                          SSLEngine engine = c.createSSLEngine();
                          params.setNeedClientAuth(false);
                          params.setCipherSuites(engine.getEnabledCipherSuites());
                          params.setProtocols(engine.getEnabledProtocols());
                          // get the default parameters
                          SSLParameters defaultSSLParameters = c.getDefaultSSLParameters();
                          params.setSSLParameters(defaultSSLParameters);
                 } catch (Exception ex) {
                          ex.printStackTrace();
                          System.out.println("Failed to create HTTPS server");
                 }
         }
});

4. Test

Open a browser (e.g. Internet Explorer), enter https://localhost:9000/ and click navigate, you will get an alert as follows:

Image 3

Due to the reason that we manually created a self-signed certificate and not issued from CA, it is not recognized by browser. Therefore, we got a security alert. Click continue and we will see the server status.

Image 4

You can test other request handlers, e.g. echoHeader, echoGet, echoPost (see the last article for handler details).

Test echoHeader handler:

Image 5

Test echoGet handler:

Image 6

History

  • 24th October, 2015: First version

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
Canada Canada
Andy Feng is a software analyst/developer based in Toronto, Canada. He has 9+ years experience in software design and development. He specializes in Java/J2EE and .Net solutions, focusing on Spring, Hibernate, JavaFX, ASP.NET MVC, Entity framework, Web services, JQuery, SQL and related technologies.

Follow up with my blogs at: http://andyfengc.github.io/

Comments and Discussions

 
PraiseThanks for this demo! Pin
ChrisDD6929-Jul-20 3:26
ChrisDD6929-Jul-20 3:26 
QuestionHave you tried with simple webpages on this server Pin
Member 1055644417-Apr-19 0:09
Member 1055644417-Apr-19 0:09 
QuestionCan anyone review this tutorial please? Pin
Member 1411917215-Jan-19 20:37
Member 1411917215-Jan-19 20:37 
Questiona small typo in the example code Pin
Member 138066191-May-18 6:45
Member 138066191-May-18 6:45 
PraiseThank you so much Pin
Kandido28-Oct-15 8:07
Kandido28-Oct-15 8:07 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.