- Class HttpsServer
- Constructor Summary
- Method Summary
- Methods declared in class com.sun.net.httpserver.HttpServer
- Methods declared in class java.lang.Object
- Constructor Details
- HttpsServer
- Method Details
- create
- create
- setHttpsConfigurator
- getHttpsConfigurator
- Class HttpServer
- Create an HTTPS Server in Java
- Create an HTTPS Server in Java
- Simple Java HTTPS server
- Prerequisites
- Creating a Simple HTTPS Server
- Conclusion
- Java https web server
- Constructor Summary
- Method Summary
- Methods inherited from class com.sun.net.httpserver.HttpServer
- Methods inherited from class java.lang.Object
- Constructor Detail
- HttpsServer
- Method Detail
- create
- create
- setHttpsConfigurator
- getHttpsConfigurator
Class HttpsServer
A HttpsServer must have an associated HttpsConfigurator object which is used to establish the SSL configuration for the SSL connections.
All other configuration is the same as for HttpServer .
Constructor Summary
Method Summary
Create a HttpsServer instance which will bind to the specified InetSocketAddress (IP address and port number).
Methods declared in class com.sun.net.httpserver.HttpServer
Methods declared in class java.lang.Object
Constructor Details
HttpsServer
Method Details
create
Creates a HttpsServer instance which is initially not bound to any local address/port. The HttpsServer is acquired from the currently installed HttpServerProvider . The server must be bound using HttpServer.bind(InetSocketAddress,int) before it can be used. The server must also have a HttpsConfigurator established with setHttpsConfigurator(HttpsConfigurator) .
create
Create a HttpsServer instance which will bind to the specified InetSocketAddress (IP address and port number). A maximum backlog can also be specified. This is the maximum number of queued incoming connections to allow on the listening socket. Queued TCP connections exceeding this limit may be rejected by the TCP implementation. The HttpsServer is acquired from the currently installed HttpServerProvider . The server must have a HttpsConfigurator established with setHttpsConfigurator(HttpsConfigurator) .
setHttpsConfigurator
getHttpsConfigurator
Report a bug or suggest an enhancement
For further API reference and developer documentation see the Java SE Documentation, which contains more detailed, developer-targeted descriptions with conceptual overviews, definitions of terms, workarounds, and working code examples. Other versions.
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 1993, 2023, Oracle and/or its affiliates, 500 Oracle Parkway, Redwood Shores, CA 94065 USA.
All rights reserved. Use is subject to license terms and the documentation redistribution policy.
Class HttpServer
This class implements a simple HTTP server. A HttpServer is bound to an IP address and port number and listens for incoming TCP connections from clients on this address. The sub-class HttpsServer implements a server which handles HTTPS requests.
One or more HttpHandler objects must be associated with a server in order to process requests. Each such HttpHandler is registered with a root URI path which represents the location of the application or service on this server. The mapping of a handler to a HttpServer is encapsulated by a HttpContext object. HttpContexts are created by calling createContext(String,HttpHandler) . Any request for which no handler can be found is rejected with a 404 response. Management of threads can be done external to this object by providing a Executor object. If none is provided a default implementation is used.
Mapping request URIs to HttpContext paths
When a HTTP request is received, the appropriate HttpContext (and handler) is located by finding the context whose path is the longest matching prefix of the request URI’s path. Paths are matched literally, which means that the strings are compared case sensitively, and with no conversion to or from any encoded forms. For example, given a HttpServer with the following HttpContexts configured:
Context | Context path |
---|---|
ctx1 | «/» |
ctx2 | «/apps/» |
ctx3 | «/apps/foo/» |
The following table shows some request URIs and which, if any context they would match with:
Request URI | Matches context |
---|---|
«http://foo.com/apps/foo/bar» | ctx3 |
«http://foo.com/apps/Foo/bar» | no match, wrong case |
«http://foo.com/apps/app1» | ctx2 |
«http://foo.com/foo» | ctx1 |
Note about socket backlogs
When binding to an address and port number, the application can also specify an integer backlog parameter. This represents the maximum number of incoming TCP connections which the system will queue internally. Connections are queued while they are waiting to be accepted by the HttpServer . When the limit is reached, further connections may be rejected (or possibly ignored) by the underlying TCP implementation. Setting the right backlog value is a compromise between efficient resource usage in the TCP layer (not setting it too high) and allowing adequate throughput of incoming requests (not setting it too low).
Create an HTTPS Server in Java
The Secure Hypertext Transfer Protocol (HTTPS) is a secured protocol that ensures safe communication through the internet. The HTTPS uses a pair of private keys and a digital certificate to verify the receiver and sender.
This tutorial will demonstrate creating a simple HTTPS server in Java.
Create an HTTPS Server in Java
Open Command Prompt as an administrator.
Go to the path of the Java bin directory in cmd.
Now run the following command:
keytool -genkeypair -keyalg RSA -alias selfsigned -keystore testkey.jks -storepass password -validity 360 -keysize 2048
This command will ask you your Lastname, Organizational unit, Organization, City, State, and two-letter country code. Provide all the info.
Type yes and press Enter as the last step.
This means the testkey.jks file has been generated in the bin folder, copy it to your Java project folder to load it in the program.
Once the Keystore and Truststore are generated, we can create an HTTPS server in JAVA.
package delftstack; import java.io.*; import java.net.InetSocketAddress; import com.sun.net.httpserver.HttpsServer; import java.security.KeyStore; import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.TrustManagerFactory; import com.sun.net.httpserver.*; import javax.net.ssl.SSLEngine; import javax.net.ssl.SSLParameters; import javax.net.ssl.SSLContext; import com.sun.net.httpserver.HttpExchange; import com.sun.net.httpserver.HttpHandler; import com.sun.net.httpserver.HttpsExchange; public class HTTPS_Server public static class MyHandler implements HttpHandler @Override public void handle(HttpExchange x) throws IOException String Response = "This is the response from delftstack"; HttpsExchange HTTPS_Exchange = (HttpsExchange) x; x.getResponseHeaders().add("Access-Control-Allow-Origin", "*"); x.sendResponseHeaders(200, Response.getBytes().length); OutputStream Output_Stream = x.getResponseBody(); Output_Stream.write(Response.getBytes()); Output_Stream.close(); > > public static void main(String[] args) throws Exception try // setup the socket address InetSocketAddress Inet_Address = new InetSocketAddress(9000); //initialize the HTTPS server HttpsServer HTTPS_Server = HttpsServer.create(Inet_Address, 0); SSLContext SSL_Context = SSLContext.getInstance("TLS"); // initialise the keystore char[] Password = "password".toCharArray(); KeyStore Key_Store = KeyStore.getInstance("JKS"); FileInputStream Input_Stream = new FileInputStream("testkey.jks"); Key_Store.load(Input_Stream, Password); // setup the key manager factory KeyManagerFactory Key_Manager = KeyManagerFactory.getInstance("SunX509"); Key_Manager.init(Key_Store, Password); // setup the trust manager factory TrustManagerFactory Trust_Manager = TrustManagerFactory.getInstance("SunX509"); Trust_Manager.init(Key_Store); // setup the HTTPS context and parameters SSL_Context.init(Key_Manager.getKeyManagers(), Trust_Manager.getTrustManagers(), null); HTTPS_Server.setHttpsConfigurator(new HttpsConfigurator(SSL_Context) public void configure(HttpsParameters params) try // initialise the SSL context SSLContext SSL_Context = getSSLContext(); SSLEngine SSL_Engine = SSL_Context.createSSLEngine(); params.setNeedClientAuth(false); params.setCipherSuites(SSL_Engine.getEnabledCipherSuites()); params.setProtocols(SSL_Engine.getEnabledProtocols()); // Set the SSL parameters SSLParameters SSL_Parameters = SSL_Context.getSupportedSSLParameters(); params.setSSLParameters(SSL_Parameters); System.out.println("The HTTPS server is connected"); > catch (Exception ex) System.out.println("Failed to create the HTTPS port"); > > >); HTTPS_Server.createContext("/test", new MyHandler()); HTTPS_Server.setExecutor(null); // creates a default executor HTTPS_Server.start(); > catch (Exception exception) System.out.println("Failed to create HTTPS server on port " + 9000 + " of localhost"); exception.printStackTrace(); > > >
The code above creates a local host HTTPS server at port number 9000, which can be used for anything.
The HTTPS server is connected
Simple Java HTTPS server
HTTPS stands for Hypertext Transfer Protocol Secure. It is a protocol for secure communication over the internet. HTTPS is widely used to secure communication between web servers and clients, but it can also be used to secure communication between other types of servers and clients. In this guide, we will learn how to create a simple HTTPS server in Java.
Prerequisites
To follow along with this guide, you will need:
- Java Development Kit (JDK) 8 or higher
- An Integrated Development Environment (IDE) such as Eclipse or IntelliJ IDEA
Creating a Simple HTTPS Server
To create a simple HTTPS server, we will use the `HttpsServer` class from the `com.sun.net.httpserver` package. This class is a part of the Java SE API and is available in JDK 8 or higher versions.
Here is an example code that creates a simple HTTPS server:
import com.sun.net.httpserver.*; import java.io.*; import java.net.InetSocketAddress; import java.security.KeyStore; import javax.net.ssl.*; public class SimpleHttpsServer < public static void main(String[] args) throws Exception < String keystorePath = "path/to/keystore"; String keystorePassword = "keystore_password"; int port = 8080; HttpsServer server = HttpsServer.create(new InetSocketAddress(port), 0); SSLContext sslContext = SSLContext.getInstance("TLS"); // Initialize the SSL context with the keystore char[] password = keystorePassword.toCharArray(); KeyStore ks = KeyStore.getInstance("JKS"); FileInputStream fis = new FileInputStream(keystorePath); ks.load(fis, password); KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509"); kmf.init(ks, password); TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509"); tmf.init(ks); sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null); // Set the HTTPS server parameters server.setHttpsConfigurator(new HttpsConfigurator(sslContext) < public void configure(HttpsParameters params) < try < // Initialize the SSL context SSLContext context = getSSLContext(); SSLEngine engine = context.createSSLEngine(); params.setNeedClientAuth(false); params.setCipherSuites(engine.getEnabledCipherSuites()); params.setProtocols(engine.getEnabledProtocols()); // Get the default parameters SSLParameters defaultSSLParameters = context.getDefaultSSLParameters(); params.setSSLParameters(defaultSSLParameters); >catch (Exception ex) < System.err.println("Failed to create HTTPS port"); >> >); // Create a context for the HTTPS server HttpContext context = server.createContext("/", new MyHandler()); server.setExecutor(null); server.start(); > static class MyHandler implements HttpHandler < public void handle(HttpExchange exchange) throws IOException < String response = "This is a simple HTTPS server"; exchange.sendResponseHeaders(200, response.getBytes().length); OutputStream output = exchange.getResponseBody(); output.write(response.getBytes()); output.flush(); output.close(); >> >
In this code, we create an HTTPS server on port 8080. We also specify the path to the keystore and the keystore password. The keystore file contains the SSL certificate that is used to secure the communication between the server and the client.
The `HttpsServer` class creates a server object that listens on the specified port. We then create an SSL context with the keystore using the `SSLContext.getInstance(“TLS”)` method. We also set up the HTTPS server parameters using the `HttpsConfigurator` class. The `MyHandler` class handles the requests that are sent to the server.
Conclusion
Creating an HTTPS server in Java is a straightforward process. The `HttpsServer` class provides a simple way to create an HTTPS server, and the `com.sun.net.httpserver` package contains all the necessary classes and interfaces to configure and run the server. With this guide, you should be able to create a simple HTTPS server in Java that can be used to secure communication between clients and servers.
Java https web server
This class is an extension of HttpServer which provides support for HTTPS. A HttpsServer must have an associated HttpsConfigurator object which is used to establish the SSL configuration for the SSL connections. All other configuration is the same as for HttpServer.
Constructor Summary
Method Summary
Create a HttpsServer instance which will bind to the specified InetSocketAddress (IP address and port number) A maximum backlog can also be specified.
Methods inherited from class com.sun.net.httpserver.HttpServer
Methods inherited from class java.lang.Object
Constructor Detail
HttpsServer
Method Detail
create
public static HttpsServer create() throws IOException
creates a HttpsServer instance which is initially not bound to any local address/port. The HttpsServer is acquired from the currently installed HttpServerProvider The server must be bound using HttpServer.bind(InetSocketAddress,int) before it can be used. The server must also have a HttpsConfigurator established with setHttpsConfigurator(HttpsConfigurator)
create
public static HttpsServer create(InetSocketAddress addr, int backlog) throws IOException
Create a HttpsServer instance which will bind to the specified InetSocketAddress (IP address and port number) A maximum backlog can also be specified. This is the maximum number of queued incoming connections to allow on the listening socket. Queued TCP connections exceeding this limit may be rejected by the TCP implementation. The HttpsServer is acquired from the currently installed HttpServerProvider The server must have a HttpsConfigurator established with setHttpsConfigurator(HttpsConfigurator)