|
| 1 | +package robaho.net.httpserver; |
| 2 | + |
| 3 | +import org.testng.annotations.Test; |
| 4 | + |
| 5 | +import java.io.IOException; |
| 6 | +import java.net.InetSocketAddress; |
| 7 | +import java.net.Proxy; |
| 8 | +import java.net.URISyntaxException; |
| 9 | +import java.net.URL; |
| 10 | + |
| 11 | +import javax.net.ssl.HostnameVerifier; |
| 12 | +import javax.net.ssl.HttpsURLConnection; |
| 13 | +import javax.net.ssl.SSLContext; |
| 14 | +import javax.net.ssl.SSLSession; |
| 15 | + |
| 16 | +import static org.testng.Assert.assertTrue; |
| 17 | + |
| 18 | +import com.sun.net.httpserver.HttpExchange; |
| 19 | +import com.sun.net.httpserver.HttpsConfigurator; |
| 20 | +import com.sun.net.httpserver.HttpsExchange; |
| 21 | +import com.sun.net.httpserver.HttpsParameters; |
| 22 | +import com.sun.net.httpserver.HttpsServer; |
| 23 | + |
| 24 | +import jdk.test.lib.net.SimpleSSLContext; |
| 25 | +import jdk.test.lib.net.URIBuilder; |
| 26 | + |
| 27 | +public class SSLSessionTest { |
| 28 | + volatile boolean hasSslSession = false; |
| 29 | + @Test |
| 30 | + public void TestHasSslSession() throws IOException, URISyntaxException { |
| 31 | + int port = 8443; |
| 32 | + |
| 33 | + var httpsServer = HttpsServer.create(new InetSocketAddress(port), 8192); |
| 34 | + var ctx = new SimpleSSLContext().get(); |
| 35 | + httpsServer.setHttpsConfigurator(new MyHttpsConfigurator (ctx)); |
| 36 | + httpsServer.createContext("/test", (HttpExchange he) -> { |
| 37 | + var sslSession = (HttpsExchange)he; |
| 38 | + hasSslSession = sslSession!=null; |
| 39 | + he.sendResponseHeaders(200,0); |
| 40 | + try (var os = he.getResponseBody()) { |
| 41 | + os.write("Hello".getBytes()); |
| 42 | + } |
| 43 | + }); |
| 44 | + httpsServer.start(); |
| 45 | + try { |
| 46 | + URL url = URIBuilder.newBuilder() |
| 47 | + .scheme("https") |
| 48 | + .loopback() |
| 49 | + .port(httpsServer.getAddress().getPort()) |
| 50 | + .path("/test") |
| 51 | + .toURL(); |
| 52 | + HttpsURLConnection urlc = (HttpsURLConnection)url.openConnection(Proxy.NO_PROXY); |
| 53 | + urlc.setSSLSocketFactory (ctx.getSocketFactory()); |
| 54 | + urlc.setHostnameVerifier (new DummyVerifier()); |
| 55 | + urlc.getInputStream().readAllBytes(); |
| 56 | + assertTrue(urlc.getResponseCode()==200); |
| 57 | + } finally { |
| 58 | + httpsServer.stop(0); |
| 59 | + } |
| 60 | + assertTrue(hasSslSession); |
| 61 | + } |
| 62 | + |
| 63 | + class MyHttpsConfigurator extends HttpsConfigurator { |
| 64 | + public MyHttpsConfigurator(SSLContext context) { |
| 65 | + super(context); |
| 66 | + } |
| 67 | + |
| 68 | + @Override |
| 69 | + public void configure(HttpsParameters params) { |
| 70 | + super.configure(params); |
| 71 | + } |
| 72 | + } |
| 73 | + public class DummyVerifier implements HostnameVerifier { |
| 74 | + @Override |
| 75 | + public boolean verify(String s, SSLSession s1) { |
| 76 | + return true; |
| 77 | + } |
| 78 | + } |
| 79 | +} |
0 commit comments