`

HttpServer源码

阅读更多
/**<pre>
Provides a simple high-level Http server API, which can be used to build embedded HTTP servers. 
Both "http" and "https" are supported. 
The API provides a partial implementation of RFC 2616 (HTTP 1.1) and RFC 2818 (HTTP over TLS). 
Any HTTP functionality not provided by this API can be implemented by application code 
using the API. 

Programmers must implement the HttpHandler interface. 
This interface provides a callback which is invoked to handle incoming requests from clients. 
A HTTP request and its response is known as an exchange.

The HttpServer class is used to listen for incoming TCP connections and it dispatches requests 
on these connections to handlers which have been registered with the server.

For sensitive information, a HttpsServer can be used to process "https" requests secured by the SSL or 
TLS protocols. A HttpsServer must be provided with a HttpsConfigurator object, 
which contains an initialized SSLContext. HttpsConfigurator can be used to configure the cipher suites and 
other SSL operating parameters. A simple example SSLContext could be created as follows: 

char[] passphrase = "passphrase".toCharArray();
KeyStore ks = KeyStore.getInstance("JKS");
ks.load(new FileInputStream("testkeys"), passphrase);

KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
kmf.init(ks, passphrase);

TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
tmf.init(ks);

SSLContext ssl = SSLContext.getInstance("TLS");
ssl.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);

The following code shows how the SSLContext is then used in a HttpsConfigurator and how the SSLContext 
and HttpsConfigurator are linked to the HttpsServer.  

server.setHttpsConfigurator (new HttpsConfigurator(sslContext) {
    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();
    if (remote.equals (...) ) {
        // modify the default set for client x
    }

    params.setSSLParameters(sslparams);
    // statement above could throw IAE if any params invalid.
    // eg. if app has a UI and parameters supplied by a user.

    }
});
</pre> */

public class HttpServerDemo {
    public static void main(String[] args) throws IOException {
        startHttpServer();
    }

    static void startHttpServer() throws IOException {
        int port = 8888;
        InetSocketAddress addr = new InetSocketAddress(port);
        HttpServer server = HttpServer.create(addr, 0);

        server.createContext("/myApp", new MyHandler());

        //server.setExecutor(null); // creates a default executor
        server.setExecutor(Executors.newCachedThreadPool());
        server.start();
        System.out.println("Server is listening on port " + port + "...");
    }
}

class MyHandler implements HttpHandler {
    public void handle(HttpExchange exchange) throws IOException {
        String requestMethod = exchange.getRequestMethod();
        System.out.println("RequestMethod: " + requestMethod);

        if (requestMethod.equalsIgnoreCase("GET")) {
            Headers responseHeaders = exchange.getResponseHeaders();
            responseHeaders.set("Content-Type", "text/html"); //text/plain
            exchange.sendResponseHeaders(200, 0);

            OutputStream responseBody = exchange.getResponseBody();
            Headers requestHeaders = exchange.getRequestHeaders();
            Set<String> keySet = requestHeaders.keySet();
            Iterator<String> iter = keySet.iterator();
            while (iter.hasNext()) {
                String key = iter.next();
                List<String> values = requestHeaders.get(key);
                String s = "<b>" + key + "</b> = " + values.toString() + "<br>";
                responseBody.write(s.getBytes());
            }
            responseBody.close();
        }
    }
}
分享到:
评论

相关推荐

    HTTP server源码

    一个HTTP 服务器的源码... 简单易懂 共享给大家

    java HttpServer源码工程

    Java HttpServer源码工程是一个基于Java平台实现的轻量级HTTP服务器项目,它允许开发者创建自己的Web服务,处理HTTP请求并返回响应。这个工程的核心在于理解如何使用Java NIO(非阻塞I/O)和Java网络编程来构建一个...

    http server源码实例

    在这个源码实例中,我们关注的是一个名为"SimpleHttpServer"的简单HTTP服务器的实现。通过深入理解这个源码,我们可以学习到HTTP服务器的基本工作原理和关键组件。 首先,让我们了解HTTP服务器的核心功能。HTTP...

    libuv-httpserver-源码.rar

    《深入剖析libuv-httpserver源码》 libuv是一个跨平台的异步I/O库,由Node.js项目发展而来,其强大的性能和易用性使其在各种系统编程中备受青睐。而libuv-httpserver则是基于libuv构建的一个HTTP服务器框架,它提供...

    基于c开发的一个超轻量型 HTTP Server源码.zip

    收到一个 HTTP 请求时(其实就是 listen 的端口 accpet 的时候),派生一个线程运行 accept_request 函数。 取出 HTTP 请求中的 method (GET 或 POST) 和 url。对于 GET 方法,如果有携带参数,则 query_string ...

    HttpServer C#

    本知识点主要聚焦于如何使用C#实现一个HttpServer,并通过WinForms(Windows Forms)来启动这个服务器。让我们深入探讨一下这个主题。 首先,`HttpServer C#`指的是使用C#语言构建一个HTTP服务器,这通常是通过实现...

    安装apache http server详细步骤

    - 下载 Apache HTTP Server 版本为 2.4.12 的源码包。 - 将下载好的 `httpd-2.4.12.tar.gz` 文件保存到 `/export/home/apache` 目录下。 #### 二、解压源码包 在 `/export/home/apache` 目录中,执行以下命令来...

    http服务器源码--java版(适合学习)

    在提供的HttpServer源码中,可能会看到以下关键部分: 1. **Server启动**:`new ServerSocket(port)` 创建监听端口的ServerSocket。 2. **接收连接**:`serverSocket.accept()` 接受客户端连接,返回Socket对象。 3....

    Delphi XE开发HTTPSERVER服务+源码+测试可用

    //关键字:Delphi XE8、HTTPSERVER、application/json //服务程序运行了几个月,基本正常,偶尔会出现异步操作异常(因所有连接都是共享同一个ado连接的原因) //以下部分关键代码供参考; TMainForm = class(TForm)...

    AspWebServer 源码

    通过对AspWebServer源码的学习和研究,开发者可以深入了解Web服务器的工作原理,提升网络编程能力,同时也为自定义和扩展Web服务器功能打下基础。这个项目对于学习MFC和网络编程的初学者以及希望深入理解Web服务器...

    java 1.6 完整源码(包括 sun)

    这个完整的源码包包括了"sun"包,它是Oracle JDK的核心部分,包含了Java语言的关键实现以及一些核心库。 一、Java 1.6的主要特性: 1. **改进的内存管理**:Java 1.6引入了更高效的垃圾回收机制,如并行和并发的...

    DelphiXE + idHttp和HttpServer + 当客户端与服务器作数据传输的实例+(源码+测试可用)

    总结来说,本文介绍了如何利用DelphiXE的idHttp和HttpServer组件实现客户端与服务器间的HTTP通信,并提供了可运行的源码供读者实践。这不仅有助于加深对HTTP协议的理解,也有利于提升Delphi开发网络应用的能力。通过...

    AndServer-master源码

    三、AndServer源码结构解析 AndServer的源码结构清晰,主要包含以下几个部分: 1. **Core模块**:这是AndServer的核心,包括服务器启动、请求处理、路由管理等核心代码。 2. **Demo模块**:提供示例代码,帮助...

    一个完整的WEB SERVER源码

    【标题】中的“一个完整的WEB SERVER源码”指的是包含了实现Web服务器功能的全部源代码,这对于想要学习或开发Web服务器的人来说是一份宝贵的参考资料。Web服务器是互联网基础设施的关键组成部分,它接收HTTP请求,...

    java HttpServer构建http服务器

    9. **源码阅读**:对于学习更深入的理解,可以查看HttpServer的源码,了解其内部工作原理,这有助于你优化性能或定制功能。 10. **工具使用**:虽然HttpServer本身就是一个简单的工具,但它可以与其他Java库结合...

    C#版支持高并发的HTTP服务器源码

    本资源提供的“C#版支持高并发的HTTP服务器源码”正是为解决这一问题而设计的,特别适用于WINFORM程序,让你能够快速创建自定义的HTTP服务器。 首先,我们要理解HTTP服务器的工作原理。HTTP(超文本传输协议)是...

    关于Qt HttpServer的一些测试(Qt6.4.0rc)测试源码

    关于Qt HttpServer的一些测试(Qt6.4.0rc)测试源码 https://blog.csdn.net/aggs1990/article/details/126995555 CSDN审核可能较慢,如无法下载,可以过段时间再回来看下 仅供相关爱好者交流使用,请于下载24小时内...

    boa-0.94.13 webserver源码

    boa-0.94.13 Web服务器源码分析与配置指南 Boa是一款轻量级的、开源的Web服务器,适用于嵌入式系统或个人项目。版本0.94.13是其历史版本之一,尽管不如现代的Apache、Nginx等服务器功能强大,但在某些特定场景下,...

    一套优秀的基于C#开发的 HTTP web server 类库源码及例子程序

    "一套优秀的基于C#开发的 HTTP web server 类库源码及例子程序" 这个标题表明我们正在讨论的是一个使用C#编程语言编写的HTTP Web服务器实现。这里的“类库”指的是一个可重用的代码集合,用于创建Web服务器,而...

Global site tag (gtag.js) - Google Analytics