如果您对获取Vert.xHttpServerOptionsSSL错误感兴趣,那么本文将是一篇不错的选择,我们将为您详在本文中,您将会了解到关于获取Vert.xHttpServerOptionsSSL错
如果您对获取 Vert.x HttpServerOptions SSL 错误感兴趣,那么本文将是一篇不错的选择,我们将为您详在本文中,您将会了解到关于获取 Vert.x HttpServerOptions SSL 错误的详细内容,我们还将为您解答获取version失败怎么解决的相关问题,并且为您提供关于Chrome中带有python baseHTTPserver 501(不支持的方法('OPTIONS'))的CORS、com.sun.net.httpserver.HttpServer的实例源码、com.sun.net.httpserver.HttpServer,缺这个包,咋整怎么找、com.sun.net.httpserver.HttpsServer的实例源码的有价值信息。
本文目录一览:- 获取 Vert.x HttpServerOptions SSL 错误(获取version失败怎么解决)
- Chrome中带有python baseHTTPserver 501(不支持的方法('OPTIONS'))的CORS
- com.sun.net.httpserver.HttpServer的实例源码
- com.sun.net.httpserver.HttpServer,缺这个包,咋整怎么找
- com.sun.net.httpserver.HttpsServer的实例源码
获取 Vert.x HttpServerOptions SSL 错误(获取version失败怎么解决)
如何解决获取 Vert.x HttpServerOptions SSL 错误?
当我尝试在 HTTPS 模式下托管 vert.x 应用程序时出现错误。
我使用的是 JDK 版本 java-11-openjdk-headless-11.0.10.0.9。
当我尝试点击任何请求时,我收到如下错误:
javax.net.ssl.SSLException: closing inbound before receiving peer''s close_notify
at java.base/sun.security.ssl.Alert.createSSLException(Alert.java:133)
当 JDK 版本为 java-11-openjdk-headless-11.0.9.11
时,应用程序运行良好我使用的是 vert.x 4.0.3。
以下是我使用 HTTPServerOption 的方式:
SelfSignedCertificate selfSignedCertificate = SelfSignedCertificate.create();
HttpServerOptions httpServerOptions = new HttpServerOptions()
.setSsl(true)
.setEnabledSecureTransportProtocols(ENABLE_TLS_TCP)
.setKeyCertOptions(selfSignedCertificate.keyCertOptions())
.setTrustOptions(selfSignedCertificate.trustOptions());
任何输入都会非常有帮助。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)
Chrome中带有python baseHTTPserver 501(不支持的方法('OPTIONS'))的CORS
嗨,我需要一些基本身份验证的帮助,同时对python baseHTTPserver进行ajax获取/发布请求。
我能够更改python脚本中的一些代码行以发送CORS标头。当我禁用HTTP基本身份验证时,它在现代浏览器中可以正常工作。
如果启用了身份验证,则会收到501(不受支持的方法(’OPTIONS’))错误(i chrome)。
我花了几个小时寻找解决方案,现在我认为我是一个很好的方法。正如我在下面的主题中读到的HTTPRequestHandler可能会引起问题,但是我的pyton技能不足以解决问题。
如果找到有关此主题的帖子,但我无法使用我拥有的脚本来运行它。有人可以帮我使其运行吗?
任何帮助或想法将不胜感激。
# Copyright 2012-2013 Eric Ptak - trouch.com # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import threading import re import codecs import mimetypes as mime import logging from webiopi.utils import * if PYTHON_MAJOR >= 3: import http.server as BaseHTTPServer else: import BaseHTTPServer try : import _webiopi.GPIO as GPIO except: pass WEBIOPI_DOCROOT = "/usr/share/webiopi/htdocs" class HTTPServer(BaseHTTPServer.HTTPServer, threading.Thread): def __init__(self, host, port, handler, context, docroot, index, auth=None): BaseHTTPServer.HTTPServer.__init__(self, ("", port), HTTPHandler) threading.Thread.__init__(self, name="HTTPThread") self.host = host self.port = port if context: self.context = context if not self.context.startswith("/"): self.context = "/" + self.context if not self.context.endswith("/"): self.context += "/" else: self.context = "/" self.docroot = docroot if index: self.index = index else: self.index = "index.html" self.handler = handler self.auth = auth self.running = True self.start() def get_request(self): sock, addr = self.socket.accept() sock.settimeout(10.0) return (sock, addr) def run(self): info("HTTP Server binded on http://%s:%s%s" % (self.host, self.port, self.context)) try: self.serve_forever() except Exception as e: if self.running == True: exception(e) info("HTTP Server stopped") def stop(self): self.running = False self.server_close() class HTTPHandler(BaseHTTPServer.BaseHTTPRequestHandler): logger = logging.getLogger("HTTP") def log_message(self, fmt, *args): self.logger.debug(fmt % args) def log_error(self, fmt, *args): pass def version_string(self): return VERSION_STRING def checkAuthentication(self): if self.server.auth == None or len(self.server.auth) == 0: return True authHeader = self.headers.get(''Authorization'') if authHeader == None: return False if not authHeader.startswith("Basic "): return False auth = authHeader.replace("Basic ", "") if PYTHON_MAJOR >= 3: auth_hash = encrypt(auth.encode()) else: auth_hash = encrypt(auth) if auth_hash == self.server.auth: return True return False def requestAuthentication(self): self.send_response(401) self.send_header("WWW-Authenticate", ''Basic realm="webiopi"'') self.end_headers(); def sendResponse(self, code, body=None, type="text/plain"): if code >= 400: if body != None: self.send_error(code, body) else: self.send_error(code) else: self.send_response(code) self.send_header("Cache-Control", "no-cache") self.send_header("Access-Control-Allow-Origin", "*") self.send_header("Access-Control-Allow-Methods", "POST, GET") self.send_header("Access-Control-Allow-Headers", " X-Custom-Header") if body != None: self.send_header("Content-Type", type); self.end_headers(); self.wfile.write(body.encode()) def findFile(self, filepath): if os.path.exists(filepath): if os.path.isdir(filepath): filepath += "/" + self.server.index if os.path.exists(filepath): return filepath else: return filepath return None def serveFile(self, relativePath): if self.server.docroot != None: path = self.findFile(self.server.docroot + "/" + relativePath) if path == None: path = self.findFile("./" + relativePath) else: path = self.findFile("./" + relativePath) if path == None: path = self.findFile(WEBIOPI_DOCROOT + "/" + relativePath) if path == None and (relativePath.startswith("webiopi.") or relativePath.startswith("jquery")): path = self.findFile(WEBIOPI_DOCROOT + "/" + relativePath) if path == None: return self.sendResponse(404, "Not Found") realPath = os.path.realpath(path) if realPath.endswith(".py"): return self.sendResponse(403, "Not Authorized") if not (realPath.startswith(os.getcwd()) or (self.server.docroot and realPath.startswith(self.server.docroot)) or realPath.startswith(WEBIOPI_DOCROOT)): return self.sendResponse(403, "Not Authorized") (type, encoding) = mime.guess_type(path) f = codecs.open(path, encoding=encoding) data = f.read() f.close() self.send_response(200) self.send_header("Content-Type", type); self.send_header("Content-Length", os.path.getsize(realPath)) self.end_headers() self.wfile.write(data) def processRequest(self): self.request.settimeout(None) if not self.checkAuthentication(): return self.requestAuthentication() request = self.path.replace(self.server.context, "/").split(''?'') relativePath = request[0] if relativePath[0] == "/": relativePath = relativePath[1:] if relativePath == "webiopi" or relativePath == "webiopi/": self.send_response(301) self.send_header("Location", "/") self.end_headers() return params = {} if len(request) > 1: for s in request[1].split(''&''): if s.find(''='') > 0: (name, value) = s.split(''='') params[name] = value else: params[s] = None compact = False if ''compact'' in params: compact = str2bool(params[''compact'']) try: result = (None, None, None) if self.command == "GET": result = self.server.handler.do_GET(relativePath, compact) elif self.command == "POST": length = 0 length_header = ''content-length'' if length_header in self.headers: length = int(self.headers[length_header]) result = self.server.handler.do_POST(relativePath, self.rfile.read(length), compact) else: result = (405, None, None) (code, body, type) = result if code > 0: self.sendResponse(code, body, type) else: if self.command == "GET": self.serveFile(relativePath) else: self.sendResponse(404) except (GPIO.InvalidDirectionException, GPIO.InvalidChannelException, GPIO.SetupException) as e: self.sendResponse(403, "%s" % e) except ValueError as e: self.sendResponse(403, "%s" % e) except Exception as e: self.sendResponse(500) raise e def do_GET(self): self.processRequest() def do_POST(self): self.processRequest()
答案1
小编典典客户端应发出两个请求,第一个是OPTIONS,然后是GET请求。所提出的解决方案不是最佳解决方案,因为我们正在用内容回答OPTIONS请求。
def do_OPTIONS(self): self.sendResponse(200) self.processRequest() # not good!
我们应该正确回答OPTIONS请求。如果我们这样做,客户端将在收到正确答案后发出GET请求。
我收到了由CORS引起的501 Unsupported method(’OPTIONS’)(OPTIONS)),并请求“ Content-
Type:application / json; charset = utf-8”。
为了解决该错误,我在do_OPTIONS中启用了CORS,并允许客户端请求特定的内容类型。
我的解决方案:
def do_OPTIONS(self): self.send_response(200, "ok") self.send_header(''Access-Control-Allow-Origin'', ''*'') self.send_header(''Access-Control-Allow-Methods'', ''GET, OPTIONS'') self.send_header("Access-Control-Allow-Headers", "X-Requested-With") self.send_header("Access-Control-Allow-Headers", "Content-Type") self.end_headers() def do_GET(self): self.processRequest()
com.sun.net.httpserver.HttpServer的实例源码
static void run(String host,String portString,CollectorRegistry registry) throws Exception { try { int port = Integer.parseInt(portString); InetSocketAddress address = host == null ? new InetSocketAddress(port) : new InetSocketAddress(host,port); HttpServer httpServer = HttpServer.create(address,10); httpServer.createContext("/",httpExchange -> { if ("/metrics".equals(httpExchange.getRequestURI().getPath())) { respondMetrics(registry,httpExchange); } else { respondRedirect(httpExchange); } }); httpServer.start(); } catch (NumberFormatException e) { throw new RuntimeException("Failed to parse command line arguments: '" + portString + "' is not a valid port number."); } }
@BeforeClass public static void startHttpServer() throws Exception { String pathPrefixWithoutLeadingSlash; if (randomBoolean()) { pathPrefixWithoutLeadingSlash = "testPathPrefix/" + randomAsciiOfLengthBetween(1,5); pathPrefix = "/" + pathPrefixWithoutLeadingSlash; } else { pathPrefix = pathPrefixWithoutLeadingSlash = ""; } int numHttpServers = randomIntBetween(2,4); httpServers = new HttpServer[numHttpServers]; HttpHost[] httpHosts = new HttpHost[numHttpServers]; for (int i = 0; i < numHttpServers; i++) { HttpServer httpServer = createHttpServer(); httpServers[i] = httpServer; httpHosts[i] = new HttpHost(httpServer.getAddress().getHostString(),httpServer.getAddress().getPort()); } RestClientBuilder restClientBuilder = RestClient.builder(httpHosts); if (pathPrefix.length() > 0) { restClientBuilder.setPathPrefix((randomBoolean() ? "/" : "") + pathPrefixWithoutLeadingSlash); } restClient = restClientBuilder.build(); }
@Before public void stopRandomHost() { //verify that shutting down some hosts doesn't matter as long as one working host is left behind if (httpServers.length > 1 && randomBoolean()) { List<HttpServer> updatedHttpServers = new ArrayList<>(httpServers.length - 1); int nodeIndex = randomInt(httpServers.length - 1); for (int i = 0; i < httpServers.length; i++) { HttpServer httpServer = httpServers[i]; if (i == nodeIndex) { httpServer.stop(0); } else { updatedHttpServers.add(httpServer); } } httpServers = updatedHttpServers.toArray(new HttpServer[updatedHttpServers.size()]); } }
/** * Starts the http server for Graphflow web UI. */ @Override public void run() { try { HttpServer server = HttpServer.create(new InetSocketAddress(HTTP_HOST,HTTP_PORT),0); // Create a route for input query server.createContext("/query",new PlanViewerHttpHandler()); // Create a default executor server.setExecutor(null); server.start(); File webViewer = new File(PLAN_VIEWER_HTML_PATH); logger.info("Please open the Graphflow UI (link below) in a browser:"); logger.info("file://" + webViewer.getAbsolutePath()); } catch (IOException exception) { logger.error("GraphflowUIHttpServer: Failed to start"); } }
public static HTTPTestServer createProxy(HttpProtocolType protocol,HttpAuthType authType,HttpTestAuthenticator auth,HttpSchemeType schemeType,HttpHandler delegate,String path) throws IOException { Objects.requireNonNull(authType); Objects.requireNonNull(auth); HttpServer impl = createHttpServer(protocol); final HTTPTestServer server = protocol == HttpProtocolType.HTTPS ? new HttpsProxyTunnel(impl,null,delegate) : new HTTPTestServer(impl,delegate); final HttpHandler hh = server.createHandler(schemeType,auth,authType); HttpContext ctxt = impl.createContext(path,hh); server.configureAuthentication(ctxt,schemeType,authType); impl.start(); return server; }
@Override public void afterPropertiesSet() throws IOException { InetSocketAddress address = (this.hostname != null ? new InetSocketAddress(this.hostname,this.port) : new InetSocketAddress(this.port)); this.server = HttpServer.create(address,this.backlog); if (this.executor != null) { this.server.setExecutor(this.executor); } if (this.contexts != null) { for (String key : this.contexts.keySet()) { HttpContext httpContext = this.server.createContext(key,this.contexts.get(key)); if (this.filters != null) { httpContext.getFilters().addAll(this.filters); } if (this.authenticator != null) { httpContext.setAuthenticator(this.authenticator); } } } if (this.logger.isInfoEnabled()) { this.logger.info("Starting HttpServer at address " + address); } this.server.start(); }
public static void main(String[] args) throws IOException,URISyntaxException,NoSuchAlgorithmException,InterruptedException { HttpServer server = createHttpsServer(); server.start(); try { test(server,HttpClient.Version.HTTP_1_1); test(server,HttpClient.Version.HTTP_2); } finally { server.stop(0); System.out.println("Server stopped"); } }
public static void main(String[] args) throws IOException { HttpServer server = HttpServer.create(new InetSocketAddress(8081),0); server.setExecutor(Executors.newCachedThreadPool()); server.createContext("/meet",exchange -> { try { Thread.sleep(250); } catch (InterruptedException e) { } exchange.sendResponseHeaders(200,0); exchange.getResponseBody().close(); }); server.start(); }
/** * Http Server */ HttpServer startHttpServer() throws IOException { if (debug) { Logger logger = Logger.getLogger("com.sun.net.httpserver"); Handler outHandler = new StreamHandler(System.out,new SimpleFormatter()); outHandler.setLevel(Level.FInesT); logger.setLevel(Level.FInesT); logger.addHandler(outHandler); } HttpServer httpServer = HttpServer.create(new InetSocketAddress(0),0); httpServer.createContext("/flis/",new MyHandler(POST_SIZE)); httpServer.start(); return httpServer; }
public static void main(String[] args) throws IOException { responsecache.setDefault(new ThrowingCache()); HttpServer server = startHttpServer(); try { URL url = new URL("http://" + InetAddress.getLocalHost().getHostAddress() + ":" + server.getAddress().getPort() + "/NoCache/"); URLConnection uc = url.openConnection(); uc.setUseCaches(false); uc.getInputStream().close(); } finally { server.stop(0); // clear the system-wide cache handler,samevm/agentvm mode responsecache.setDefault(null); } }
public static void main(String[] args) throws Exception { HttpServer server = createServer(); int port = server.getAddress().getPort(); System.out.println("HTTP server port = " + port); httproot = "http://127.0.0.1:" + port + "/files/"; fileuri = httproot + "foo.txt"; HttpClient client = HttpClient.newHttpClient(); try { test1(); test2(); //test3(); } finally { server.stop(0); serverExecutor.shutdownNow(); for (HttpClient c : clients) ((ExecutorService)c.executor()).shutdownNow(); } }
/** * Creates and starts an HTTP or proxy server that requires * Negotiate authentication. * @param scheme "Negotiate" or "Kerberos" * @param principal the krb5 service principal the server runs with * @return the server */ public static HttpServer httpd(String scheme,boolean proxy,String principal,String ktab) throws Exception { MyHttpHandler h = new MyHttpHandler(); HttpServer server = HttpServer.create(new InetSocketAddress(0),0); HttpContext hc = server.createContext("/",h); hc.setAuthenticator(new MyServerAuthenticator( proxy,scheme,principal,ktab)); server.start(); return server; }
public static void main(String[] args) throws IOException { responsecache.setDefault(new ThrowingCache()); HttpServer server = startHttpServer(); try { URL url = new URL("http://" + InetAddress.getLocalHost().getHostAddress() + ":" + server.getAddress().getPort() + "/NoCache/"); URLConnection uc = url.openConnection(); uc.setUseCaches(false); uc.getInputStream().close(); } finally { server.stop(0); // clear the system-wide cache handler,samevm/agentvm mode responsecache.setDefault(null); } }
public static void register(HttpServer server) { // Info server.createContext("/api",new InfoController()); // Version server.createContext("/api/version",new VersionController()); // Settings server.createContext("/api/settings",new SettingsController()); // Refresh server.createContext("/api/user/refresh",new UserRefreshController()); // Events server.createContext("/api/user/events",new UserEventsController()); // Bot server.createContext("/api/bot",new BotInfoController()); server.createContext("/api/bot/start",new StartController()); server.createContext("/api/bot/stop",new StopController()); // Plugins server.createContext("/api/plugins",new PluginController()); }
public static void test() { HttpServer server = null; try { serverDigest = MessageDigest.getInstance("MD5"); clientDigest = MessageDigest.getInstance("MD5"); server = startHttpServer(); int port = server.getAddress().getPort(); out.println ("Server listening on port: " + port); client("http://localhost:" + port + "/chunked/"); if (!MessageDigest.isEqual(clientMac,serverMac)) { throw new RuntimeException( "Data received is NOT equal to the data sent"); } } catch (Exception e) { throw new RuntimeException(e); } finally { if (server != null) server.stop(0); } }
public static void main(String[] args) throws IOException { HttpServer server = HttpServer.create(new InetSocketAddress(HTTP_SERVER_PORT),0); HttpContext secureContext = server.createContext(DEMO_REST_BASIC_AUTH,new RestDemoHandler()); secureContext.setAuthenticator(new BasicAuthenticator("demo-auth") { @Override public boolean checkCredentials(String user,String pwd) { return user.equals(USERNAME) && pwd.equals(PASSWORD); } }); server.createContext(DEMO_REST_NO_AUTH,new RestDemoHandler()); server.setExecutor(null); System.out.println("[*] Waiting for messages."); server.start(); }
public WebServerTestHelper() throws IOException,IllegalArgumentException { port = DEFAULT_PORT; String inPort = System.getProperty("wlt3.test.server.port"); if(inPort!=null && !inPort.isEmpty()) { try { inPort = inPort.trim(); port = Integer.parseInt(inPort); if((port<1) || (port>65535)) { throw new IllegalArgumentException("\""+inPort+"\" is not a valid TCP port for standalone web server listener! Valid TCP ports: 0-65535"); } } catch(Exception e) { throw new IllegalArgumentException("\""+inPort+"\" is not a valid TCP port for standalone web server listener!"); } } hs = HttpServer.create(new InetSocketAddress(port),0); sr = new SecureRandom(); accessList = new Hashtable<String,String>(); hs.start(); }
static void initServer() throws Exception { Logger logger = Logger.getLogger("com.sun.net.httpserver"); ConsoleHandler ch = new ConsoleHandler(); logger.setLevel(Level.SEVERE); ch.setLevel(Level.SEVERE); logger.addHandler(ch); String root = System.getProperty ("test.src")+ "/docs"; InetSocketAddress addr = new InetSocketAddress (0); s1 = HttpServer.create (addr,0); if (s1 instanceof HttpsServer) { throw new RuntimeException ("should not be httpsserver"); } s2 = HttpsServer.create (addr,0); HttpHandler h = new FileServerHandler(root); HttpContext c1 = s1.createContext("/files",h); HttpContext c2 = s2.createContext("/files",h); HttpContext c3 = s1.createContext("/echo",new EchoHandler()); redirectHandler = new RedirectHandler("/redirect"); redirectHandlerSecure = new RedirectHandler("/redirect"); HttpContext c4 = s1.createContext("/redirect",redirectHandler); HttpContext c41 = s2.createContext("/redirect",redirectHandlerSecure); HttpContext c5 = s2.createContext("/echo",new EchoHandler()); HttpContext c6 = s1.createContext("/keepalive",new KeepAliveHandler()); redirectErrorHandler = new RedirectErrorHandler("/redirecterror"); redirectErrorHandlerSecure = new RedirectErrorHandler("/redirecterror"); HttpContext c7 = s1.createContext("/redirecterror",redirectErrorHandler); HttpContext c71 = s2.createContext("/redirecterror",redirectErrorHandlerSecure); delayHandler = new DelayHandler(); HttpContext c8 = s1.createContext("/delay",delayHandler); HttpContext c81 = s2.createContext("/delay",delayHandler); executor = Executors.newCachedThreadPool(); s1.setExecutor(executor); s2.setExecutor(executor); ctx = new SimpleSSLContext().get(); sslparams = ctx.getSupportedSSLParameters(); s2.setHttpsConfigurator(new Configurator(ctx)); s1.start(); s2.start(); port = s1.getAddress().getPort(); System.out.println("HTTP server port = " + port); httpsport = s2.getAddress().getPort(); System.out.println("HTTPS server port = " + httpsport); httproot = "http://127.0.0.1:" + port + "/"; httpsroot = "https://127.0.0.1:" + httpsport + "/"; proxy = new ProxyServer(0,false); proxyPort = proxy.getPort(); System.out.println("Proxy port = " + proxyPort); }
@Override public void init(DaemonContext context) throws DaemonInitException,Exception { if (!config.init(context.getArguments())) throw new DaemonInitException("Invalid configuration."); ClassLoader loader = SPLDaemon.class.getClassLoader(); InputStream params = loader.getResourceAsstream(DEFAULT_ParaMS_FILE); if (params != null) { MAVLinkShadow.getInstance().loadParams(params); params.close(); } else { logger.warn("File 'default.params' with initial parameters values not found."); } MAVLinkMessageQueue mtMessageQueue = new MAVLinkMessageQueue(config.getQueueSize()); tcpserver = new MAVLinkTcpserver(config.getMAVLinkPort(),mtMessageQueue); MAVLinkMessageQueue moMessageQueue = new MAVLinkMessageQueue(config.getQueueSize()); MOMessageHandler moHandler = new MOMessageHandler(moMessageQueue); httpServer = HttpServer.create(new InetSocketAddress(config.getRockblockPort()),0); httpServer.createContext(config.getHttpContext(),new RockBlockHttpHandler(moHandler,config.getRockBlockIMEI())); httpServer.setExecutor(null); // Todo: broadcast MO messages to all the connected clients. RockBlockClient rockblock = new RockBlockClient(config.getRockBlockIMEI(),config.getRockBlockUsername(),config.getRockBlockPassword(),config.getRockBlockURL()); MTMessagePump mtMsgPump = new MTMessagePump(mtMessageQueue,rockblock); mtMsgPumpThread = new Thread(mtMsgPump,"mt-message-pump"); WSEndpoint.setMTQueue(mtMessageQueue); wsServer = new Server("localhost",config.getWSPort(),"/gcs",WSEndpoint.class); }
private static HttpServer createHttpServer() throws Exception { HttpServer httpServer = MockHttpServer.createHttp(new InetSocketAddress(InetAddress.getLoopbackAddress(),0),0); httpServer.start(); //returns a different status code depending on the path for (int statusCode : getAllStatusCodes()) { httpServer.createContext(pathPrefix + "/" + statusCode,new ResponseHandler(statusCode)); } return httpServer; }
private static HttpServer createHttpServer() throws Exception { HttpServer httpServer = MockHttpServer.createHttp(new InetSocketAddress(InetAddress.getLoopbackAddress(),new ResponseHandler(statusCode)); } return httpServer; }
@AfterClass public static void stopHttpServers() throws IOException { restClient.close(); restClient = null; for (HttpServer httpServer : httpServers) { httpServer.stop(0); } httpServers = null; }
public static void initServer() throws IOException { Logger logger = Logger.getLogger("com.sun.net.httpserver"); ConsoleHandler ch = new ConsoleHandler(); logger.setLevel(Level.ALL); ch.setLevel(Level.ALL); logger.addHandler(ch); String root = System.getProperty("test.src") + "/docs"; InetSocketAddress addr = new InetSocketAddress(0); httpServer = HttpServer.create(addr,0); if (httpServer instanceof HttpsServer) { throw new RuntimeException("should not be httpsserver"); } httpsServer = HttpsServer.create(addr,0); HttpHandler h = new FileServerHandler(root); HttpContext c1 = httpServer.createContext("/files",h); HttpContext c2 = httpsServer.createContext("/files",h); HttpContext c3 = httpServer.createContext("/echo",new EchoHandler()); redirectHandler = new RedirectHandler("/redirect"); redirectHandlerSecure = new RedirectHandler("/redirect"); HttpContext c4 = httpServer.createContext("/redirect",redirectHandler); HttpContext c41 = httpsServer.createContext("/redirect",redirectHandlerSecure); HttpContext c5 = httpsServer.createContext("/echo",new EchoHandler()); HttpContext c6 = httpServer.createContext("/keepalive",new KeepAliveHandler()); redirectErrorHandler = new RedirectErrorHandler("/redirecterror"); redirectErrorHandlerSecure = new RedirectErrorHandler("/redirecterror"); HttpContext c7 = httpServer.createContext("/redirecterror",redirectErrorHandler); HttpContext c71 = httpsServer.createContext("/redirecterror",redirectErrorHandlerSecure); delayHandler = new DelayHandler(); HttpContext c8 = httpServer.createContext("/delay",delayHandler); HttpContext c81 = httpsServer.createContext("/delay",delayHandler); executor = Executors.newCachedThreadPool(); httpServer.setExecutor(executor); httpsServer.setExecutor(executor); ctx = new SimpleSSLContext().get(); httpsServer.setHttpsConfigurator(new HttpsConfigurator(ctx)); httpServer.start(); httpsServer.start(); port = httpServer.getAddress().getPort(); System.out.println("HTTP server port = " + port); httpsport = httpsServer.getAddress().getPort(); System.out.println("HTTPS server port = " + httpsport); httproot = "http://127.0.0.1:" + port + "/"; httpsroot = "https://127.0.0.1:" + httpsport + "/"; proxy = new ProxyServer(0,false); proxyPort = proxy.getPort(); System.out.println("Proxy port = " + proxyPort); }
static LocalHttpServer startServer() throws IOException { HttpServer httpServer = HttpServer.create( new InetSocketAddress(0),0); LocalHttpServer localHttpServer = new LocalHttpServer(httpServer); localHttpServer.start(); return localHttpServer; }
static HttpServer createServer(ExecutorService e,BasicAuthenticator sa) throws Exception { HttpServer server = HttpServer.create(new InetSocketAddress(0),10); Handler h = new Handler(); HttpContext serverContext = server.createContext("/test",h); serverContext.setAuthenticator(sa); server.setExecutor(e); server.start(); return server; }
public static void main(String[] args) throws IOException { banner(); int port = 8000; HttpServer server = HttpServer.create(new InetSocketAddress(port),0); server.createContext("/",new HTTPHandler()); server.setExecutor(null); // creates a default executor server.start(); System.out.println("\nJRE Version: "+System.getProperty("java.version")); System.out.println("[INFO]: Listening on port "+port); System.out.println(); }
public static void main(String[] args) throws IOException { HttpServer server = HttpServer.create(new InetSocketAddress(8080),new LandingPageHandler()); server.createContext("/post",new PostHandler()); server.createContext("/json",new JSONHandler()); server.createContext("/favicon.ico",new IgnoreHandler()); server.setExecutor(Executors.newCachedThreadPool()); server.start(); System.out.println("Server started on port 8080" ); }
private void init() { try { server = HttpServer.create(new InetSocketAddress(8900),0); server.createContext("/sparql",new GetSparqlResult(this)); } catch (Exception exception) { fail(exception.getMessage()); } }
private void createContext(HttpServer server,String path,HttpHandler handler,Authenticator auth) { final HttpContext context = server.createContext(path,handler); if( auth != null ) { context.setAuthenticator(auth); } context.getFilters().addAll(filters); }
public static void main(String[] args) throws Exception { HttpServer server = HttpServer.create(new InetSocketAddress(0),0); try { server.setExecutor(Executors.newFixedThreadPool(1)); server.createContext(someContext,new HttpHandler() { @Override public void handle(HttpExchange msg) { try { try { msg.sendResponseHeaders(noMsgCode,-1); } catch(IOException ioe) { ioe.printstacktrace(); } } finally { msg.close(); } } }); server.start(); System.out.println("Server started at port " + server.getAddress().getPort()); runRawSocketHttpClient("localhost",server.getAddress().getPort()); } finally { ((ExecutorService)server.getExecutor()).shutdown(); server.stop(0); } System.out.println("Server finished."); }
public GameStateIntegration(int port) { this.locale = new Locale("/lang/en-US.lang","en-US"); // Make sure to load our locale try { this.server = HttpServer.create(new InetSocketAddress(port),0); // Make our http server this.server.createContext("/",this); this.server.setExecutor(null); this.server.start(); Courier.getInstance().getLogger().info("Initiated GSI http server!"); } catch (IOException e) { e.printstacktrace(); } }
@Override public void afterPropertiesSet() throws Exception { if (this.server == null) { InetSocketAddress address = (this.hostname != null ? new InetSocketAddress(this.hostname,this.port) : new InetSocketAddress(this.port)); this.server = HttpServer.create(address,this.backlog); if (this.logger.isInfoEnabled()) { this.logger.info("Starting HttpServer at address " + address); } this.server.start(); this.localServer = true; } super.afterPropertiesSet(); }
public void start() throws IOException { this.server = HttpServer.create(new InetSocketAddress(this.port),0); this.server.createContext("/",new DIALServer(this.piy,this.port)); this.server.setExecutor(null); this.server.start(); }
static LocalHttpServer startServer() throws IOException { HttpServer httpServer = HttpServer.create( new InetSocketAddress(0),0); LocalHttpServer localHttpServer = new LocalHttpServer(httpServer); localHttpServer.start(); return localHttpServer; }
@Override public void run() { try { server = HttpServer.create(new InetSocketAddress(port),5); server.createContext("/abc",serverListener); server.start(); } catch (IOException e) { logger.error("Error in creating test server.",e); } }
public L2Acpserver() { HttpServer server; try { server = HttpServer.create(new InetSocketAddress(8000),0); server.createContext("/api",new RequestHandler()); server.setExecutor(null); // creates a default executor server.start(); } catch (IOException e) { // Todo Auto-generated catch block e.printstacktrace(); } ThreadPool.scheduleAtFixedrate(new DatamineTask(),120000,600000); }
private JNLPServer(int port,String hostname) throws IOException { httpServer = HttpServer.create(new InetSocketAddress(port),0); Properties ps = new Properties(); InputStream stream = getClass().getResourceAsstream( "/com/ramussoft/lib.conf"); ps.load(stream); stream.close(); httpServer.createContext("/",new ResourceServlet(hostname,new Date( Long.parseLong(ps.getProperty("LastModified"))))); httpServer.setExecutor(Executors.newCachedThreadPool()); }
@Test(expected = PiloSAException.class) public void importFailNot200() throws IOException { HttpServer server = runImportFailsHttpServer(); try (PilosaClient client = PilosaClient.withAddress(":15999")) { StaticBitIterator iterator = new StaticBitIterator(); try { client.importFrame(this.index.frame("importframe"),iterator); } finally { if (server != null) { server.stop(0); } } } }
@Test(expected = PiloSAException.class) public void queryFail404test() throws IOException { HttpServer server = runcontentSizeLyingHttpServer("/404"); try (PilosaClient client = PilosaClient.withAddress(":15999")) { try { client.query(this.frame.setBit(15,10)); } finally { if (server != null) { server.stop(0); } } } }
private static HttpServer newHttpServer(HttpProtocolType protocol) throws IOException { switch (protocol) { case HTTP: return HttpServer.create(); case HTTPS: return HttpsServer.create(); default: throw new InternalError("Unsupported protocol " + protocol); } }
com.sun.net.httpserver.HttpServer,缺这个包,咋整怎么找
com.sun.net.httpserver.HttpServer,缺这个包,咋整怎么找
com.sun.net.httpserver.HttpsServer的实例源码
public static void initServer() throws Exception { String portstring = System.getProperty("port.number"); port = portstring != null ? Integer.parseInt(portstring) : 0; portstring = System.getProperty("port.number1"); proxyPort = portstring != null ? Integer.parseInt(portstring) : 0; Logger logger = Logger.getLogger("com.sun.net.httpserver"); ConsoleHandler ch = new ConsoleHandler(); logger.setLevel(Level.ALL); ch.setLevel(Level.ALL); logger.addHandler(ch); String root = System.getProperty ("test.src")+ "/docs"; InetSocketAddress addr = new InetSocketAddress (port); s1 = HttpServer.create (addr,0); if (s1 instanceof HttpsServer) { throw new RuntimeException ("should not be httpsserver"); } HttpHandler h = new FileServerHandler (root); HttpContext c = s1.createContext ("/files",h); HttpHandler h1 = new RedirectHandler ("/redirect"); HttpContext c1 = s1.createContext ("/redirect",h1); executor = Executors.newCachedThreadPool(); s1.setExecutor (executor); s1.start(); if (port == 0) port = s1.getAddress().getPort(); else { if (s1.getAddress().getPort() != port) throw new RuntimeException("Error wrong port"); System.out.println("Port was assigned by Driver"); } System.out.println("HTTP server port = " + port); httproot = "http://127.0.0.1:" + port + "/files/"; redirectroot = "http://127.0.0.1:" + port + "/redirect/"; uri = new URI(httproot); fileuri = httproot + "foo.txt"; }
public static void main(String[] args) throws Exception { Logger logger = Logger.getLogger("com.sun.net.httpserver"); logger.setLevel(Level.ALL); logger.info("TEST"); System.out.println("Sending " + REQUESTS + " requests; delay=" + INSERT_DELAY + ",chunks=" + CHUNK_SIZE + ",XFixed=" + XFIXED); SSLContext ctx = new SimpleSSLContext().get(); InetSocketAddress addr = new InetSocketAddress(0); HttpsServer server = HttpsServer.create(addr,0); server.setHttpsConfigurator(new Configurator(ctx)); HttpClient client = HttpClient.newBuilder() .sslContext(ctx) .build(); try { test(server,client); System.out.println("OK"); } finally { server.stop(0); ((ExecutorService)client.executor()).shutdownNow(); } }
static HttpServer createHttpsServer() throws IOException,NoSuchAlgorithmException { HttpsServer server = com.sun.net.httpserver.HttpsServer.create(); HttpContext context = server.createContext(PATH); context.setHandler(new HttpHandler() { @Override public void handle(HttpExchange he) throws IOException { he.getResponseHeaders().add("encoding","UTF-8"); he.sendResponseHeaders(200,RESPONSE.length()); he.getResponseBody().write(RESPONSE.getBytes(StandardCharsets.UTF_8)); he.close(); } }); server.setHttpsConfigurator(new Configurator(SSLContext.getDefault())); server.bind(new InetSocketAddress(InetAddress.getLoopbackAddress(),0),0); return server; }
@Override public HttpServer createHttpServerInstance(final int port) throws IOException { try { final HttpsServer server = HttpsServer.create(new InetSocketAddress(port),5); server.setHttpsConfigurator(new HttpsConfigurator(sslContext) { @Override public void configure(final HttpsParameters params) { final SSLContext c = getSSLContext(); // get the default parameters final SSLParameters sslparams = c.getDefaultSSLParameters(); params.setSSLParameters(sslparams); // statement above Could throw IAE if any params invalid. // eg. if app has a UI and parameters supplied by a user. } }); s_logger.info("create HTTPS server instance on port: " + port); return server; } catch (final Exception ioe) { s_logger.error(ioe.toString(),ioe); } return null; }
@Test public void testHttps() throws Exception { KeyStore ks = getKeyStore(); KeyManagerFactory kmf = KeyManagerFactory.getInstance("simplepemreload"); kmf.init( ExpiringCacheKeyManagerParameters.forKeyStore(ks).withRevalidation(5) ); KeyManager[] km = kmf.getKeyManagers(); assertthat(km).hasSize(1); SSLContext ctx = SSLContext.getInstance("TLSv1"); ctx.init(km,null,null); HttpsServer server = startHttpsServer(ctx); try { HttpsURLConnection conn = createClientConnection(); assertthat(conn.getPeerPrincipal().getName()).isEqualTo("CN=anna.apn2.com"); } finally { // stop server server.stop(0); } }
protected HttpsServer startHttpsServer(SSLContext ctx) throws Exception { InetSocketAddress localhost = new InetSocketAddress("127.0.0.59",59995); HttpsServer server = HttpsServer.create(localhost,0); server.setHttpsConfigurator(new HttpsConfigurator(ctx)); server.createContext("/",(t) -> { byte[] data = "success".getBytes(); t.sendResponseHeaders(HttpURLConnection.HTTP_OK,data.length); OutputStream o = t.getResponseBody(); o.write(data); o.close(); }); server.setExecutor(null); server.start(); return server; }
/** * Internal method which creates and starts the server. * * @param httpsMode True if the server to be started is HTTPS,false otherwise. * @return Started server. */ private static GridEmbeddedHttpServer createAndStart(boolean httpsMode) throws Exception { HttpServer httpSrv; InetSocketAddress addrToBind = new InetSocketAddress(HOSTNAME_TO_BIND_SRV,getAvailablePort()); if (httpsMode) { HttpsServer httpsSrv = HttpsServer.create(addrToBind,0); httpsSrv.setHttpsConfigurator(new HttpsConfigurator(GridTestUtils.sslContext())); httpSrv = httpsSrv; } else httpSrv = HttpServer.create(addrToBind,0); GridEmbeddedHttpServer embeddedHttpSrv = new GridEmbeddedHttpServer(); embeddedHttpSrv.proto = httpsMode ? "https" : "http"; embeddedHttpSrv.httpSrv = httpSrv; embeddedHttpSrv.httpSrv.start(); return embeddedHttpSrv; }
private static HttpServer initHttpsServer(InputStream keystoreInputSteam,char[] password) throws IOException { try { KeyStore ks = KeyStore.getInstance("JKS"); ks.load(keystoreInputSteam,password); KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509"); kmf.init(ks,password); TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509"); tmf.init(ks); SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(kmf.getKeyManagers(),tmf.getTrustManagers(),null); HttpsServer httpsServer = HttpsServer.create(); httpsServer.setHttpsConfigurator(new HttpsConfigurator(sslContext)); return httpsServer; } catch (NoSuchAlgorithmException | CertificateException | KeyStoreException | UnrecoverableKeyException | KeyManagementException e) { throw new RuntimeException(e); } }
public void start(HttpsServerProperties properties,SSLContext sslContext,HttpHandler handler) throws Exception { logger.info("start {}",properties); executor = new ThreadPoolExecutor(100,200,60,TimeUnit.SECONDS,new ArrayBlockingQueue<Runnable>(10)); name = handler.getClass().getSimpleName(); executor.setRejectedExecutionHandler(this); InetSocketAddress socketAddress = new InetSocketAddress(properties.getPort()); httpsServer = HttpsServer.create(socketAddress,16); httpsServer.setHttpsConfigurator(HttpsConfiguratorFactory. createHttpsConfigurator(sslContext,properties.isClientAuth())); httpsServer.setExecutor(executor); httpsServer.createContext("/",handler); httpsServer.start(); logger.info("init {}",properties); }
static HttpServer createServer() throws Exception { HttpServer s = HttpServer.create(new InetSocketAddress(0),0); if (s instanceof HttpsServer) throw new RuntimeException ("should not be httpsserver"); String root = System.getProperty("test.src") + "/docs"; s.createContext("/files",new FileServerHandler(root)); s.setExecutor(serverExecutor); s.start(); return s; }
static void initServer() throws Exception { Logger logger = Logger.getLogger("com.sun.net.httpserver"); ConsoleHandler ch = new ConsoleHandler(); logger.setLevel(Level.SEVERE); ch.setLevel(Level.SEVERE); logger.addHandler(ch); String root = System.getProperty ("test.src")+ "/docs"; InetSocketAddress addr = new InetSocketAddress (0); s1 = HttpServer.create (addr,0); if (s1 instanceof HttpsServer) { throw new RuntimeException ("should not be httpsserver"); } s2 = HttpsServer.create (addr,0); HttpHandler h = new FileServerHandler(root); HttpContext c1 = s1.createContext("/files",h); HttpContext c2 = s2.createContext("/files",h); HttpContext c3 = s1.createContext("/echo",new EchoHandler()); redirectHandler = new RedirectHandler("/redirect"); redirectHandlerSecure = new RedirectHandler("/redirect"); HttpContext c4 = s1.createContext("/redirect",redirectHandler); HttpContext c41 = s2.createContext("/redirect",redirectHandlerSecure); HttpContext c5 = s2.createContext("/echo",new EchoHandler()); HttpContext c6 = s1.createContext("/keepalive",new KeepAliveHandler()); redirectErrorHandler = new RedirectErrorHandler("/redirecterror"); redirectErrorHandlerSecure = new RedirectErrorHandler("/redirecterror"); HttpContext c7 = s1.createContext("/redirecterror",redirectErrorHandler); HttpContext c71 = s2.createContext("/redirecterror",redirectErrorHandlerSecure); delayHandler = new DelayHandler(); HttpContext c8 = s1.createContext("/delay",delayHandler); HttpContext c81 = s2.createContext("/delay",delayHandler); executor = Executors.newCachedThreadPool(); s1.setExecutor(executor); s2.setExecutor(executor); ctx = new SimpleSSLContext().get(); sslparams = ctx.getSupportedSSLParameters(); s2.setHttpsConfigurator(new Configurator(ctx)); s1.start(); s2.start(); port = s1.getAddress().getPort(); System.out.println("HTTP server port = " + port); httpsport = s2.getAddress().getPort(); System.out.println("HTTPS server port = " + httpsport); httproot = "http://127.0.0.1:" + port + "/"; httpsroot = "https://127.0.0.1:" + httpsport + "/"; proxy = new ProxyServer(0,false); proxyPort = proxy.getPort(); System.out.println("Proxy port = " + proxyPort); }
public static void initServer() throws IOException { Logger logger = Logger.getLogger("com.sun.net.httpserver"); ConsoleHandler ch = new ConsoleHandler(); logger.setLevel(Level.ALL); ch.setLevel(Level.ALL); logger.addHandler(ch); String root = System.getProperty("test.src") + "/docs"; InetSocketAddress addr = new InetSocketAddress(0); httpServer = HttpServer.create(addr,0); if (httpServer instanceof HttpsServer) { throw new RuntimeException("should not be httpsserver"); } httpsServer = HttpsServer.create(addr,0); HttpHandler h = new FileServerHandler(root); HttpContext c1 = httpServer.createContext("/files",h); HttpContext c2 = httpsServer.createContext("/files",h); HttpContext c3 = httpServer.createContext("/echo",new EchoHandler()); redirectHandler = new RedirectHandler("/redirect"); redirectHandlerSecure = new RedirectHandler("/redirect"); HttpContext c4 = httpServer.createContext("/redirect",redirectHandler); HttpContext c41 = httpsServer.createContext("/redirect",redirectHandlerSecure); HttpContext c5 = httpsServer.createContext("/echo",new EchoHandler()); HttpContext c6 = httpServer.createContext("/keepalive",new KeepAliveHandler()); redirectErrorHandler = new RedirectErrorHandler("/redirecterror"); redirectErrorHandlerSecure = new RedirectErrorHandler("/redirecterror"); HttpContext c7 = httpServer.createContext("/redirecterror",redirectErrorHandler); HttpContext c71 = httpsServer.createContext("/redirecterror",redirectErrorHandlerSecure); delayHandler = new DelayHandler(); HttpContext c8 = httpServer.createContext("/delay",delayHandler); HttpContext c81 = httpsServer.createContext("/delay",delayHandler); executor = Executors.newCachedThreadPool(); httpServer.setExecutor(executor); httpsServer.setExecutor(executor); ctx = new SimpleSSLContext().get(); httpsServer.setHttpsConfigurator(new HttpsConfigurator(ctx)); httpServer.start(); httpsServer.start(); port = httpServer.getAddress().getPort(); System.out.println("HTTP server port = " + port); httpsport = httpsServer.getAddress().getPort(); System.out.println("HTTPS server port = " + httpsport); httproot = "http://127.0.0.1:" + port + "/"; httpsroot = "https://127.0.0.1:" + httpsport + "/"; proxy = new ProxyServer(0,false); proxyPort = proxy.getPort(); System.out.println("Proxy port = " + proxyPort); }
private static HttpServer newHttpServer(HttpProtocolType protocol) throws IOException { switch (protocol) { case HTTP: return HttpServer.create(); case HTTPS: return HttpsServer.create(); default: throw new InternalError("Unsupported protocol " + protocol); } }
static HttpsServer configure(HttpsServer server) throws IOException { try { SSLContext ctx = SSLContext.getDefault(); server.setHttpsConfigurator(new Configurator(ctx)); } catch (NoSuchAlgorithmException ex) { throw new IOException(ex); } return server; }
public static void initServer() throws IOException { Logger logger = Logger.getLogger("com.sun.net.httpserver"); ConsoleHandler ch = new ConsoleHandler(); logger.setLevel(Level.ALL); ch.setLevel(Level.ALL); logger.addHandler(ch); String root = System.getProperty("test.src") + "/docs"; InetSocketAddress addr = new InetSocketAddress(0); httpServer = HttpServer.create(addr,false); proxyPort = proxy.getPort(); System.out.println("Proxy port = " + proxyPort); }
private static HttpsServer createHttpsServer(int port) throws Exception { generateCertificate(); HttpsServer httpsServer = HttpsServer.create(new InetSocketAddress(port),0); SSLContext sslContext = getSslContext(); httpsServer.setHttpsConfigurator(new HttpsConfigurator(sslContext)); return httpsServer; }
@Override public Archive<?> createAuxiliaryArchive() { JavaArchive arquillianPactConsumer = null; arquillianPactConsumer = ShrinkWrap.create(JavaArchive.class,"arquillian-pact-consumer.jar") // Add Core classes required in container part .addClasses(AbstractConsumerPactTest.class,RemoteConsumerPactTest.class,PactConsumerConfiguration.class,MockProviderConfigCreator.class,PactConsumerConfigurator.class,PactConsumerRemoteExtension.class,PactFilesCommand.class,ConsumerProviderPair.class,PactMismatchesException.class,ConsumerPactRunnerKt.class,HttpHandler.class,HttpServer.class,HttpServerProvider.class,ResolveClassAnnotation.class,StubServer.class,StubServerEnricher.class,HttpsServer.class,HttpContext.class) .addPackages(true,Pact.class.getPackage()) .addAsServiceProvider(RemoteLoadableExtension.class,PactConsumerRemoteExtension.class); arquillianPactConsumer = addSunHttpServer(arquillianPactConsumer); final Properties properties = pactConsumerConfigurationInstance.get().asProperties(); String configuration = toString(properties); arquillianPactConsumer.add(new StringAsset(configuration),"/pact-consumer-configuration.properties"); final JavaArchive[] pactConsumerDeps = Maven.resolver() .resolve("au.com.dius:pact-jvm-consumer_2.11:" + getVersion()) .withtransitivity().as(JavaArchive.class); final JavaArchive merge = merge(arquillianPactConsumer,pactConsumerDeps); return merge; }
@Test public void testHttps() throws Exception { KeyStore ks = getKeyStore(); KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); kmf.init(ks,new char[0]); KeyManager[] km = kmf.getKeyManagers(); assertthat(km).hasSize(1); SSLContext ctx = SSLContext.getInstance("TLSv1"); ctx.init(km,null); HttpsServer server = startHttpsServer(ctx); try { HttpsURLConnection conn = createClientConnection(); assertthat(conn.getPeerPrincipal().getName()).isEqualTo("CN=anna.apn2.com"); } finally { // stop server server.stop(0); } }
public static void startHttpsServer() throws CertificateException,IOException,KeyManagementException,KeyStoreException,NoSuchAlgorithmException,UnrecoverableKeyException { HttpsServer httpsServer = HttpsServer.create(new InetSocketAddress(443),0); char[] keystorePassword = "password".tochararray(); SSLContext sslContext = SSLContext.getInstance("TLS"); KeyStore keyStore = KeyStore.getInstance("JKS"); keyStore.load(new FileInputStream("keystore.jks"),keystorePassword); KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("SunX509"); keyManagerFactory.init(keyStore,keystorePassword); sslContext.init(keyManagerFactory.getKeyManagers(),null); HttpsConfigurator configurator = new HttpsConfigurator(sslContext); httpsServer.createContext("/example",new ExampleHandler()); httpsServer.setHttpsConfigurator(configurator); httpsServer.setExecutor(null); httpsServer.start(); }
protected void startHttpsServer() throws Exception { final InetSocketAddress addr = new InetSocketAddress(httpsServerPort); httpsServer = HttpsServer.create(addr,0); httpsServer.setExecutor(Executors.newCachedThreadPool()); attachHttpHandlers(httpsServer); final char[] passphrase = KEYSTORE_PASSWORD.tochararray(); final KeyStore ks = KeyStore.getInstance("JKS"); ks.load(getKeyStore(),passphrase); final KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); kmf.init(ks,passphrase); final TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); tmf.init(ks); final SSLContext ssl = SSLContext.getInstance("TLS"); ssl.init(kmf.getKeyManagers(),null); httpsServer.setHttpsConfigurator(new HttpsConfigurator(ssl) { @Override public void configure(final HttpsParameters params) { final SSLContext c = getSSLContext(); final SSLParameters sslparams = c.getDefaultSSLParameters(); params.setSSLParameters(sslparams); } }); httpsServer.start(); }
@Override public HttpServer createHttpServerInstance(int port) throws IOException { try { HttpsServer server = HttpsServer.create(new InetSocketAddress(port),5); server.setHttpsConfigurator(new HttpsConfigurator(sslContext) { @Override public void configure(HttpsParameters params) { // get the remote address if needed InetSocketAddress remote = params.getClientAddress(); SSLContext c = getSSLContext(); // get the default parameters SSLParameters sslparams = c.getDefaultSSLParameters(); params.setSSLParameters(sslparams); params.setProtocols(SSLUtils.getRecommendedProtocols()); params.setCipherSuites(SSLUtils.getRecommendedCiphers()); // statement above Could throw IAE if any params invalid. // eg. if app has a UI and parameters supplied by a user. } }); s_logger.info("create HTTPS server instance on port: " + port); return server; } catch (Exception ioe) { s_logger.error(ioe.toString(),ioe); } return null; }
@Before public void setup() throws Exception { inetSocketAddress = mock(InetSocketAddress.class); httpsServer = powermockito.mock(HttpsServer.class); sslContext = powermockito.mock(SSLContext.class); keyManagerFactory = powermockito.mock(KeyManagerFactory.class); keyStore = powermockito.mock(KeyStore.class); trustManagerFactory = powermockito.mock(TrustManagerFactory.class); powermockito.mockStatic(KeyManagerFactory.class); powermockito.mockStatic(KeyStore.class); powermockito.mockStatic(SSLContext.class); powermockito.mockStatic(HttpsServer.class); powermockito.mockStatic(TrustManagerFactory.class); when(KeyManagerFactory.getInstance("SunX509")).thenReturn(keyManagerFactory); when(KeyStore.getInstance("JKS")).thenReturn(keyStore); when(SSLContext.getInstance("TLS")).thenReturn(sslContext); when(HttpsServer.create(inetSocketAddress,-1)).thenReturn(httpsServer); when(TrustManagerFactory.getInstance("SunX509")).thenReturn(trustManagerFactory); simpleHttpsServerfactorybean = new SimpleHttpsServerfactorybean(); InputStream inputStream = mock(InputStream.class); Resource keyStoreLocation = mock(Resource.class); when(keyStoreLocation.getInputStream()).thenReturn(inputStream); simpleHttpsServerfactorybean.setKeyStoreLocation(keyStoreLocation); }
@Test public void shouldReturnHttpsServerOnGetobject() throws Exception { // setup when(HttpsServer.create(isA(InetSocketAddress.class),eq(-1))).thenReturn(httpsServer); simpleHttpsServerfactorybean.afterPropertiesSet(); // act HttpsServer result = (HttpsServer) simpleHttpsServerfactorybean.getobject(); // assert assertthat(result,equalTo(httpsServer)); }
@SuppressWarnings("unchecked") @Test public void shouldReturnHttpsServerOnGetobjectType() throws Exception { // setup when(HttpsServer.create(isA(InetSocketAddress.class),eq(-1))).thenReturn(httpsServer); simpleHttpsServerfactorybean.afterPropertiesSet(); // act Class result = simpleHttpsServerfactorybean.getobjectType(); // assert assertEquals(HttpsServer.class,result.getSuperclass()); }
public ServicePublisher() throws Exception { LOGGER.info("keystore = " + KEYSTORE); LOGGER.info(String.format("url = https://%s:%s%s",HOSTNAME,PORT,PATH)); httpsServer = HttpsServer.create(new InetSocketAddress(HOSTNAME,PORT),0); httpsServer.setHttpsConfigurator(createHttpsConfigurator()); endpoint = Endpoint.create(new GreetingService()); }
public ServicePublisher() throws Exception { LOGGER.info("keystore = " + KEYSTORE); LOGGER.info(String.format("url = https://%s:%s%s",PATH)); httpsServer = HttpsServer.create(new InetSocketAddress(HOSTNAME,0); httpsServer.setHttpsConfigurator(createHttpsConfigurator()); endpoint = Endpoint.create(new PingService()); }
private static HttpServer setUpHttps(JSONObject config) throws Exception { HttpServer server = HttpsServer.create(new InetSocketAddress(config.getInt("httpsPort")),0); SSLContext sslContext = SSLContext.getInstance("TLS"); // initialise the keystore char[] password = "84267139".tochararray(); KeyStore ks = KeyStore.getInstance("JKS"); FileInputStream fis = new FileInputStream("www_turtledev_org.jks"); ks.load(fis,password); // setup the key manager factory KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509"); kmf.init(ks,password); // setup the trust manager factory TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509"); tmf.init(ks); // setup the HTTPS context and parameters sslContext.init(kmf.getKeyManagers(),null); ((HttpsServer) server).setHttpsConfigurator(new HttpsConfigurator(sslContext) { @Override 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 (NoSuchAlgorithmException ex) { System.out.println("Failed to create HTTPS port"); } } }); return server; }
public void initHttpsServer(int port,String sslPassword) { try { this.server = HttpsServer.create(new InetSocketAddress(port),0); SSLContext sslContext = SSLContext.getInstance("TLS"); char[] password = sslPassword.tochararray(); KeyStore ks = KeyStore.getInstance("JKS"); FileInputStream fis = new FileInputStream("https_key.jks"); 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(),null); this.server.setHttpsConfigurator(new HttpsConfigurator(sslContext) { @Override public void configure(HttpsParameters params) { try { SSLContext c = SSLContext.getDefault(); SSLEngine engine = c.createSSLEngine(); params.setNeedClientAuth(false); params.setCipherSuites(engine.getEnabledCipherSuites()); params.setProtocols(engine.getEnabledProtocols()); SSLParameters defaultSSLParameters = c.getDefaultSSLParameters(); params.setSSLParameters(defaultSSLParameters); } catch (Exception ex) { System.out.println("Failed to create HTTPS port"); } } }); this.server.setExecutor(null); // creates a default executor } catch (Exception e) { System.out.println("Exception while starting RequestListener."); e.printstacktrace(); } }
@Override public HttpsServer createHttpsServer(InetSocketAddress addr,int backlog) throws IOException { throw new UnsupportedOperationException(); }
public void Start(int port) { try { // load certificate String keystoreFilename = Constants.KEY_STORE_FILE; char[] storepass = Constants.KEY_STORE_PASSWORD.tochararray(); char[] keypass = Constants.KEY_STORE_PASSWORD.tochararray(); FileInputStream fIn = new FileInputStream(Constants.SERVER_PATH + keystoreFilename); KeyStore keystore = KeyStore.getInstance(KEY_STORE); keystore.load(fIn,storepass); // setup the key manager factory KeyManagerFactory kmf = KeyManagerFactory.getInstance(KEY_MANAGER_FACTORY); kmf.init(keystore,keypass); // setup the trust manager factory TrustManagerFactory tmf = TrustManagerFactory.getInstance(KEY_MANAGER_FACTORY); tmf.init(keystore); // 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(),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) { System.err.println(Errors.START_HTTPS_SERVER); } } }); System.out.println(SERVER_STARTED + port); server.createContext(ROOT_ENDPOINT,new OAuthHandler.RootHandler()); server.createContext(OAUTH_ENDPOINT,new OAuthHandler.AuthorizationHandler()); server.createContext(REDIRECT_ENDPOINT,new OAuthHandler.RedirectUriHandler()); server.setExecutor(null); server.start(); } catch (Exception e) { System.err.println(e); } }
public Boolean start() { try { final Integer maxQueue = 256; final Executor executor = Executors.newFixedThreadPool(maxQueue); if (_useEncryption) { final HttpsServer httpsServer = HttpsServer.create(new InetSocketAddress(_tlsPort),maxQueue); final TlsCertificate tlsCertificate = TlsFactory.loadTlsCertificate(StringUtil.bytesToString(IoUtil.getFileContents(_certificateFile)),IoUtil.getFileContents(_certificateKeyFile)); final SSLContext sslContext = TlsFactory.createContext(tlsCertificate); httpsServer.setHttpsConfigurator(new HttpsConfigurator(sslContext) { @Override public void configure(final HttpsParameters params) { params.setProtocols(new String[]{ "TLSv1.1","TLSv1.2","TLSv1.3" }); params.setNeedClientAuth(false); } }); _applyEndpoints(httpsServer); httpsServer.setExecutor(executor); _tlsServer = httpsServer; _tlsServer.start(); } if (! _disableHttp) { _server = com.sun.net.httpserver.HttpServer.create(new InetSocketAddress(_port),maxQueue); if (_redirectToTls) { _server.createContext("/",new HttpHandler(_encryptionRedirectEndpoint,false)); } else { _applyEndpoints(_server); } _server.setExecutor(executor); _server.start(); } return true; } catch (final Exception e) { e.printstacktrace(); return false; } }
/** * Initialize HttpServer instance * @throws Exception */ public void init() throws Exception { InetAddress host = null; if (ProcessEditorServerHelper.getHost() != null) { host = InetAddress.getByName(ProcessEditorServerHelper.getHost()); } if (host != null) { // Bind to specific interface address = new InetSocketAddress(host,port); } else { // Bind to all interfaces System.out.println("BINDING TO ALL INTERFACES"); address = new InetSocketAddress(port); } //secure = true; if (ProcessEditorServerHelper.isSecure()) { KeyStore ks = KeyStore.getInstance("JKS"); char[] pwd = "inubit".tochararray(); ks.load(ProcessEditorServer.class.getResourceAsstream(KEY_STORE),pwd); KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509"); kmf.init(ks,pwd); TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509"); tmf.init(ks); SSLContext ssl = SSLContext.getInstance("TLS"); ssl.init(kmf.getKeyManagers(),null); this.server = HttpsServer.create(address,255); ((HttpsServer) this.server).setHttpsConfigurator(new HttpsConfigurator(ssl) { public void configure(HttpsParameters params) { // get the remote address if needed InetSocketAddress remote = params.getClientAddress(); SSLContext c = getSSLContext(); // get the default parameters SSLParameters sslparams = c.getDefaultSSLParameters(); params.setSSLParameters(sslparams); // statement above Could throw IAE if any params invalid. // eg. if app has a UI and parameters supplied by a user. } }); } else { this.server = HttpServer.create(address,255); } System.out.println("[Server] Setting up server at " + address.getAddress().getHostAddress() + ":" + address.getPort()); logger.info("[Server] Setting up server at " + address.getAddress().getHostAddress() + ":" + address.getPort()); for (AbstractHandler h : handlers) { server.createContext(h.getContextUri(),h); } BlockingQueue queue = new ProcessEditorBlockingQueue(1000); ThreadPoolExecutor exec = new ProcessEditorThreadPoolExecutor(10,20,5000,TimeUnit.MILLISECONDS,queue); TemporaryKeyManager.initialize(); server.setExecutor(exec); // creates executor this.setup = true; }
public void before(final Description description) throws Exception { this.service = Executors.newFixedThreadPool( threadCount,new ThreadFactoryBuilder().setDaemon(true).setNameFormat("TestHttpServer-%d").build()); InetSocketAddress inetSocketAddress = new InetSocketAddress("localhost",0); if (hasSsl) { byte[] sampleTruststore1 = Base64.decode(TEST_TS1); byte[] sampleKeystore1 = Base64.decode(TEST_KS1); keystore = File.createTempFile("SecureAcceptAllGetTest",".keystore"); truststore = File.createTempFile("SecureAcceptAllGetTest",".truststore"); FileOutputStream keystoreFileOut = new FileOutputStream(keystore); try { keystoreFileOut.write(sampleKeystore1); } finally { keystoreFileOut.close(); } FileOutputStream truststoreFileOut = new FileOutputStream(truststore); try { truststoreFileOut.write(sampleTruststore1); } finally { truststoreFileOut.close(); } KeyStore ks = KeyStore.getInstance("JKS"); ks.load(new FileInputStream(keystore),PASSWORD.tochararray()); KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); kmf.init(ks,PASSWORD.tochararray()); KeyStore ts = KeyStore.getInstance("JKS"); ts.load(new FileInputStream(truststore),PASSWORD.tochararray()); TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); tmf.init(ts); SSLContext sc = SSLContext.getInstance("TLS"); sc.init(kmf.getKeyManagers(),null); HttpsServer secureServer = HttpsServer.create(inetSocketAddress,0); secureServer.setHttpsConfigurator(new HttpsConfigurator(sc) { public void configure (HttpsParameters params) { SSLContext c = getSSLContext(); SSLParameters sslparams = c.getDefaultSSLParameters(); params.setSSLParameters(sslparams); } }); server = secureServer; } else { server = HttpServer.create(inetSocketAddress,0); } server.setExecutor(service); for (Entry<String,HttpHandler> handler : handlers.entrySet()) { server.createContext(handler.getKey(),handler.getValue()); } server.start(); localHttpServerPort = server.getAddress().getPort(); System.out.println(description.getClassName() + " TestServer is started: " + getServerUrl()); }
@Override public HttpsServer createHttpsServer(InetSocketAddress addr,int backlog) throws IOException { throw new UnsupportedOperationException(); }
@Test public void testHttps() throws Exception { copyCertKey("certchain.pem","key.pem"); KeyStore ks = getKeyStore(); KeyManagerFactory kmf = KeyManagerFactory.getInstance("simplepemreload"); kmf.init( ExpiringCacheKeyManagerParameters.forKeyStore(ks).withRevalidation(5) ); KeyManager[] km = kmf.getKeyManagers(); assertthat(km).hasSize(1); SSLContext ctx = SSLContext.getInstance("TLSv1"); ctx.init(km,null); HttpsServer server = startHttpsServer(ctx); try { HttpsURLConnection conn = createClientConnection(); assertthat(conn.getPeerPrincipal().getName()).isEqualTo("CN=anna.apn2.com"); Thread.sleep(1000); // avoid very quick overwriting of file in case of quick test run copyCertKey("selfcert.pem","selfkey.pem"); Thread.sleep(15000); // wait for picking up the change in 5 seconds (+extra) HttpsURLConnection conn2 = createClientConnection(); assertthat(conn2.getPeerPrincipal().getName()).isEqualTo("CN=self.signed.cert,O=Radical Research,ST=NA,C=IO"); } finally { // stop server server.stop(0); } }
/** * Provides the HttpsConfigurator for https fine tuning * * @return the HttpsConfigurator for the httpsServer */ public HttpsConfigurator getHttpsConfigurator() { return ((HttpsServer) httpServer).getHttpsConfigurator(); }
/** * Creates the actual instance of the https server with the given parameters * * @param inetSocketAddress InetSocketAddress to bind the HttpsServer to * @param backlogSize Backlog size for this server instance * @return HttpsServer instance * @throws IOException */ protected HttpServer createServer(InetSocketAddress inetSocketAddress,int backlogSize) throws IOException{ return HttpsServer.create(inetSocketAddress,backlogSize); }
今天的关于获取 Vert.x HttpServerOptions SSL 错误和获取version失败怎么解决的分享已经结束,谢谢您的关注,如果想了解更多关于Chrome中带有python baseHTTPserver 501(不支持的方法('OPTIONS'))的CORS、com.sun.net.httpserver.HttpServer的实例源码、com.sun.net.httpserver.HttpServer,缺这个包,咋整怎么找、com.sun.net.httpserver.HttpsServer的实例源码的相关知识,请在本站进行查询。
本文标签: