當前位置: 首頁>>代碼示例>>Java>>正文


Java HttpServer.start方法代碼示例

本文整理匯總了Java中com.sun.net.httpserver.HttpServer.start方法的典型用法代碼示例。如果您正苦於以下問題:Java HttpServer.start方法的具體用法?Java HttpServer.start怎麽用?Java HttpServer.start使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在com.sun.net.httpserver.HttpServer的用法示例。


在下文中一共展示了HttpServer.start方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: 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

示例2: runSample

import com.sun.net.httpserver.HttpServer; //導入方法依賴的package包/類
/**
 * Main function which runs the actual sample.
 * @param authFile the auth file backing the web server
 * @return true if sample runs successfully
 * @throws Exception exceptions running the server
 */
public static boolean runSample(File authFile) throws Exception {
    final String redirectUrl = "http://localhost:8000";
    final ExecutorService executor = Executors.newCachedThreadPool();

    try {
        DelegatedTokenCredentials credentials = DelegatedTokenCredentials.fromFile(authFile, redirectUrl);

        HttpServer server = HttpServer.create(new InetSocketAddress(8000), 0);
        HttpContext context = server.createContext("/", new MyHandler());
        context.getAttributes().put("credentials", credentials);
        server.setExecutor(Executors.newCachedThreadPool()); // creates a default executor
        server.start();

        // Use a browser to login within a minute
        Thread.sleep(60000);
        return true;
    } finally {
        executor.shutdown();
    }
}
 
開發者ID:Azure,項目名稱:azure-libraries-for-java,代碼行數:27,代碼來源:WebServerWithDelegatedCredentials.java

示例3: createServer

import com.sun.net.httpserver.HttpServer; //導入方法依賴的package包/類
public static HTTPTestServer createServer(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 = 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,代碼行數:19,代碼來源:HTTPTestServer.java

示例4: 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

示例5: startHttpServer

import com.sun.net.httpserver.HttpServer; //導入方法依賴的package包/類
/**
 * Http Server
 */
static HttpServer startHttpServer() throws IOException {
    HttpServer httpServer = HttpServer.create(new InetSocketAddress(0), 0);
    HttpHandler httpHandler = new SimpleHandler();
    httpServer.createContext("/chunked/", httpHandler);
    httpServer.start();
    return httpServer;
}
 
開發者ID:AdoptOpenJDK,項目名稱:openjdk-jdk10,代碼行數:11,代碼來源:ChunkedEncodingTest.java

示例6: main

import com.sun.net.httpserver.HttpServer; //導入方法依賴的package包/類
public static void main(String[] args) throws Exception {
     boolean error = true;

     // Start a dummy server to return 404
     HttpServer server = HttpServer.create(new InetSocketAddress(0), 0);
     HttpHandler handler = new HttpHandler() {
         public void handle(HttpExchange t) throws IOException {
             InputStream is = t.getRequestBody();
             while (is.read() != -1);
             t.sendResponseHeaders (404, -1);
             t.close();
         }
     };
     server.createContext("/", handler);
     server.start();

     // Client request
     try {
         URL url = new URL("http://localhost:" + server.getAddress().getPort());
         String name = args.length >= 2 ? args[1] : "foo.bar.Baz";
         ClassLoader loader = new URLClassLoader(new URL[] { url });
         System.out.println(url);
         Class c = loader.loadClass(name);
         System.out.println("Loaded class \"" + c.getName() + "\".");
     } catch (ClassNotFoundException ex) {
         System.out.println(ex);
         error = false;
     } finally {
         server.stop(0);
     }
     if (error)
         throw new RuntimeException("No ClassNotFoundException generated");
}
 
開發者ID:lambdalab-mirror,項目名稱:jdk8u-jdk,代碼行數:34,代碼來源:ClassLoad.java

示例7: main

import com.sun.net.httpserver.HttpServer; //導入方法依賴的package包/類
public static void main(String[] args) throws Exception {
    HttpServer server = HttpServer.create(new InetSocketAddress(0), 10);
    ExecutorService e = Executors.newCachedThreadPool();
    Handler h = new Handler();
    HttpContext serverContext = server.createContext("/test", h);
    int port = server.getAddress().getPort();
    System.out.println("Server port = " + port);

    ClientAuth ca = new ClientAuth();
    ServerAuth sa = new ServerAuth("foo realm");
    serverContext.setAuthenticator(sa);
    server.setExecutor(e);
    server.start();
    HttpClient client = HttpClient.newBuilder()
                                  .authenticator(ca)
                                  .build();

    try {
        URI uri = new URI("http://127.0.0.1:" + Integer.toString(port) + "/test/foo");
        HttpRequest req = HttpRequest.newBuilder(uri).GET().build();

        HttpResponse resp = client.send(req, asString());
        ok = resp.statusCode() == 200 && resp.body().equals(RESPONSE);

        if (!ok || ca.count != 1)
            throw new RuntimeException("Test failed");

        // repeat same request, should succeed but no additional authenticator calls

        resp = client.send(req, asString());
        ok = resp.statusCode() == 200 && resp.body().equals(RESPONSE);

        if (!ok || ca.count != 1)
            throw new RuntimeException("Test failed");

        // try a POST

        req = HttpRequest.newBuilder(uri)
                         .POST(fromString(POST_BODY))
                         .build();
        resp = client.send(req, asString());
        ok = resp.statusCode() == 200;

        if (!ok || ca.count != 1)
            throw new RuntimeException("Test failed");
    } finally {
        server.stop(0);
        e.shutdownNow();
    }
    System.out.println("OK");
}
 
開發者ID:AdoptOpenJDK,項目名稱:openjdk-jdk10,代碼行數:52,代碼來源:BasicAuthTest.java

示例8: startServer

import com.sun.net.httpserver.HttpServer; //導入方法依賴的package包/類
private static void startServer(HttpServer server, JSONObject config) throws NoSuchAlgorithmException {
        server.createContext("/api", new Server(config));
//        server.createContext("/" + config.getString("sslHost"), new HTTPSConfirmHandler(config.getString("sslTarget")));
        int poolSize = Runtime.getRuntime().availableProcessors() + 1;
        server.setExecutor(Executors.newFixedThreadPool(poolSize));
//        server.setExecutor(null);
        server.start();
    }
 
開發者ID:sherisaac,項目名稱:TurteTracker_APIServer,代碼行數:9,代碼來源:Server.java

示例9: runImportFailsHttpServer

import com.sun.net.httpserver.HttpServer; //導入方法依賴的package包/類
private HttpServer runImportFailsHttpServer() {
    final int port = 15999;
    try {
        HttpServer server = HttpServer.create(new InetSocketAddress(port), 0);
        server.createContext("/fragment/nodes", new FragmentNodesHandler());
        server.setExecutor(null);
        server.start();
        return server;
    } catch (IOException ex) {
        fail(ex.getMessage());
    }
    return null;
}
 
開發者ID:pilosa,項目名稱:java-pilosa,代碼行數:14,代碼來源:PilosaClientIT.java

示例10: runContent0HttpServer

import com.sun.net.httpserver.HttpServer; //導入方法依賴的package包/類
private HttpServer runContent0HttpServer(String path, int statusCode) {
    final int port = 15999;
    try {
        HttpServer server = HttpServer.create(new InetSocketAddress(port), 0);
        server.createContext(path, new Content0Handler(statusCode));
        server.setExecutor(null);
        server.start();
        return server;
    } catch (IOException ex) {
        fail(ex.getMessage());
    }
    return null;
}
 
開發者ID:pilosa,項目名稱:java-pilosa,代碼行數:14,代碼來源:PilosaClientIT.java

示例11: main

import com.sun.net.httpserver.HttpServer; //導入方法依賴的package包/類
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.");
}
 
開發者ID:lambdalab-mirror,項目名稱:jdk8u-jdk,代碼行數:30,代碼來源:MissingTrailingSpace.java

示例12: listen

import com.sun.net.httpserver.HttpServer; //導入方法依賴的package包/類
/**
 * Starts a server on the given port and listen for connections.
 * @param port a TCP port
 * @throws IOException if an I/O error occurs.
 */
public void listen(int port) throws IOException {
  HttpServer server = HttpServer.create(new InetSocketAddress(port), 0);
  server.createContext("/", exchange -> {
    callback.accept(() -> exchange, () -> exchange);
    exchange.close();
  });
  server.setExecutor(null);
  server.start();
}
 
開發者ID:forax,項目名稱:jexpress,代碼行數:15,代碼來源:JExpress.java

示例13: main

import com.sun.net.httpserver.HttpServer; //導入方法依賴的package包/類
public static void main(String[] args) throws Exception {
    HttpServer server = HttpServer.create(new InetSocketAddress(0), 0);
    server.createContext("/test/InfiniteLoop", new RespHandler());
    server.start();
    try {
        InetSocketAddress address = server.getAddress();
        URL url = new URL("http://localhost:" + address.getPort()
                          + "/test/InfiniteLoop");
        final Phaser phaser = new Phaser(2);
        for (int i=0; i<10; i++) {
            HttpURLConnection uc = (HttpURLConnection)url.openConnection();
            final InputStream is = uc.getInputStream();
            final Thread thread = new Thread() {
                public void run() {
                    try {
                        phaser.arriveAndAwaitAdvance();
                        while (is.read() != -1)
                            Thread.sleep(50);
                    } catch (Exception x) { x.printStackTrace(); }
                }};
            thread.start();
            phaser.arriveAndAwaitAdvance();
            is.close();
            System.out.println("returned from close");
            thread.join();
        }
    } finally {
        server.stop(0);
    }
}
 
開發者ID:AdoptOpenJDK,項目名稱:openjdk-jdk10,代碼行數:31,代碼來源:InfiniteLoop.java

示例14: startHttpServer

import com.sun.net.httpserver.HttpServer; //導入方法依賴的package包/類
HttpServer startHttpServer() throws IOException {
    HttpServer httpServer = HttpServer.create(new InetSocketAddress(0), 0);
    httpServer.createContext("/foo", new SimpleHandler());
    httpServer.start();
    return httpServer;
}
 
開發者ID:AdoptOpenJDK,項目名稱:openjdk-jdk10,代碼行數:7,代碼來源:UnmodifiableMaps.java

示例15: startHttpServer

import com.sun.net.httpserver.HttpServer; //導入方法依賴的package包/類
HttpServer startHttpServer() throws IOException {
    HttpServer httpServer = HttpServer.create(new InetSocketAddress(0), 0);
    httpServer.createContext(URI_PATH, new SimpleHandler());
    httpServer.start();
    return httpServer;
}
 
開發者ID:lambdalab-mirror,項目名稱:jdk8u-jdk,代碼行數:7,代碼來源:HttpOnly.java


注:本文中的com.sun.net.httpserver.HttpServer.start方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。