当前位置: 首页>>代码示例>>Java>>正文


Java HttpServer类代码示例

本文整理汇总了Java中com.sun.net.httpserver.HttpServer的典型用法代码示例。如果您正苦于以下问题:Java HttpServer类的具体用法?Java HttpServer怎么用?Java HttpServer使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


HttpServer类属于com.sun.net.httpserver包,在下文中一共展示了HttpServer类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: run

import com.sun.net.httpserver.HttpServer; //导入依赖的package包/类
/**
 * 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");
    }
}
 
开发者ID:graphflow,项目名称:graphflow,代码行数:20,代码来源:PlanViewerHttpServer.java

示例2: init

import com.sun.net.httpserver.HttpServer; //导入依赖的package包/类
@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);
}
 
开发者ID:envirover,项目名称:SPLGroundControl,代码行数:40,代码来源:SPLDaemon.java

示例3: run

import com.sun.net.httpserver.HttpServer; //导入依赖的package包/类
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.");
    }
}
 
开发者ID:fstab,项目名称:promagent,代码行数:18,代码来源:BuiltInServer.java

示例4: startHttpServer

import com.sun.net.httpserver.HttpServer; //导入依赖的package包/类
@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();
}
 
开发者ID:justor,项目名称:elasticsearch_my,代码行数:24,代码来源:RestClientMultipleHostsIntegTests.java

示例5: stopRandomHost

import com.sun.net.httpserver.HttpServer; //导入依赖的package包/类
@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()]);
    }
}
 
开发者ID:justor,项目名称:elasticsearch_my,代码行数:18,代码来源:RestClientMultipleHostsIntegTests.java

示例6: createProxy

import com.sun.net.httpserver.HttpServer; //导入依赖的package包/类
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, null, delegate);
    final HttpHandler hh = server.createHandler(schemeType, auth, authType);
    HttpContext ctxt = impl.createContext(path, hh);
    server.configureAuthentication(ctxt, schemeType, auth, authType);
    impl.start();

    return server;
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:22,代码来源:HTTPTestServer.java

示例7: afterPropertiesSet

import com.sun.net.httpserver.HttpServer; //导入依赖的package包/类
@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();
}
 
开发者ID:lamsfoundation,项目名称:lams,代码行数:25,代码来源:SimpleHttpServerFactoryBean.java

示例8: main

import com.sun.net.httpserver.HttpServer; //导入依赖的package包/类
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");
    }
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:17,代码来源:ProxyTest.java

示例9: main

import com.sun.net.httpserver.HttpServer; //导入依赖的package包/类
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();
}
 
开发者ID:saturnism,项目名称:istio-by-example-java,代码行数:17,代码来源:MeetingServer.java

示例10: startHttpServer

import com.sun.net.httpserver.HttpServer; //导入依赖的package包/类
/**
 * 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;
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:19,代码来源:FixedLengthInputStream.java

示例11: main

import com.sun.net.httpserver.HttpServer; //导入依赖的package包/类
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);
    }
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:17,代码来源:NoCache.java

示例12: main

import com.sun.net.httpserver.HttpServer; //导入依赖的package包/类
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();
    }
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:23,代码来源:APIErrors.java

示例13: httpd

import com.sun.net.httpserver.HttpServer; //导入依赖的package包/类
/**
 * 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;
}
 
开发者ID:lambdalab-mirror,项目名称:jdk8u-jdk,代码行数:18,代码来源:HttpNegotiateServer.java

示例14: register

import com.sun.net.httpserver.HttpServer; //导入依赖的package包/类
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());
    }
 
开发者ID:Twasi,项目名称:twasi-core,代码行数:25,代码来源:ApiRegistry.java

示例15: test

import com.sun.net.httpserver.HttpServer; //导入依赖的package包/类
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);
    }
}
 
开发者ID:lambdalab-mirror,项目名称:jdk8u-jdk,代码行数:23,代码来源:ChunkedEncodingTest.java


注:本文中的com.sun.net.httpserver.HttpServer类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。