2 Star 6 Fork 2

XieJC / TinyHttpServer

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
贡献代码
同步代码
取消
提示: 由于 Git 不支持空文件夾,创建文件夹后会生成空的 .keep 文件
Loading...
README
MIT

TinyHttpServer - 轻量Http服务器

特点

  1. 除Java语言标准库外不依赖任何类库或框架
  2. 采用基于Reactor模式的非阻塞IO,并以此提供并发环境
  3. 提供的API涵盖Http服务、请求拦截、响应、静态资源、Cookie与Session操作
  4. 附带JSON解析与生成、日志等工具类
  5. 通过堆外内存缓冲池、静态资源LRU缓存等设计使Http服务更高效

快速上手

public static void main(String[] args){
    int port = 80;
    HttpServer server = new HttpServer(port);
    server.serve("/hello",Http.Method.Get,(req,resp) -> {
       resp.write("Hello, TinyHttpServer") 
    });
    server.start();
}

API Documents

HttpServer

  • HttpServer(int port)

    最简单的HttpServer构造方法,此时工作线程数为 2 * 可用的CPU核心数,总线程数在此基础上加2

  • HttpServer(int port, int threads)

    需要端口号和工作线程数

  • public HttpServer(int port,int threads,int fileCacheSize, int cachedFileMaxSize);

    在TinyHttpServer中内嵌了File LRU Cache 对高频使用的静态资源文件进行缓存,以避免磁盘IO。 通常Web浏览器所需的Html、CSS、JS文件中大部分的大小都处于数十到数百KB之间,在内存中存储它们所耗费的空间是可以接受的。 fileCacheSize表示希望整个缓存容纳多少个静态资源文件。 cachedFileMaxSize表示被缓存的文件的最大大小,超过这个大小的文件将不予缓存。

  • void serve(String url,Http.Method method,HttpService service);

    其中Http.Method是一个enum,含:Http.Method.GETHttp.Method.PUTHttp.Method.POSTHttp.Method.DELETE 以及Http.Method.ANY如果在HttpServer.serve中传入Http.Method.ANY,相当于分别注册为GETPOST HttpService定义:

        public interface HttpService {
            void serve(HttpRequest req,HttpResponse resp);
        }

    作为函数式编程接口供人实现。

    这意味着可以将method作为Http Method访问URL为url的接口,针对这一Http Request进行的操作在HttpService对象中定义,并返回相应的Http Response

  • void filter(String urlPattern,Http.Method method,HttpFilter filter); urlPattern意味着它除了作为一个普通字符串外还能作为简单的正则表达式传入。filter也是一个单方法的接口,定义如下:

        public interface HttpFilter {
            boolean filter(HttpRequest req,HttpResponse resp);
        }

    HttpFilter.filter方法返回一个布尔值,这表示该请求是否通过。

  • void staticResourceDir(String dir); 将静态资源文件夹的路径传入,使该文件夹下的静态资源文件其能以Http的方式访问到。

HttpRequest

  • HttpSession getSession();

    获取HttpSession对象

  • setCookie(String key,String value)

    为该client的下一次的request设置Cookie

  • setCookie(String key,String value,int seconds)

    和上一则类似,加入超时时间

  • void forward(String url)

    转发请求到新的url

  • String getParam(String paramName)

    获取http request param

  • String getHeader(String headerName)

    通过获取http请求头的Key获取对应的Value

  • String getCookie(String cookieName)

    获取http cookie

  • String body()

    获取http请求体

HttpResponse

  • void setStatusCode(int code)

    设置Http应答的状态码

  • void writeText(String content)

    向Http请求体中写入字符串数据,会覆盖之前保留的内容

  • void writeText(String ...contents)

    向Http请求体中写入多个字符串数据,会覆盖之前保留的内容

  • void writeTextAppend(String content)

    向Http请求体中追加写入字符串

  • void void writeAsJSON(Object obj)

    向Http请求体中写入Java对象,会自动转为JSON格式,请为该对象保留一个默认的构造函数

  • void sendRedirect(String url)

    重定向到新的URL

  • void sendRedirectPermanently(String url)

    永久重定向到新的URL

  • void setHeader(String key,String value)

    设置Http应答的一行请求头,会追加写入

HttpSession

  • Object getAttribute(String key)

  • void setAttribute(String key , Object value)

其他示例

public static void main(String[] args) throws IOException {
        HttpServer server = new HttpServer(80,1);
        server.serve("/hello", Http.Method.GET, (req, resp) -> {
            resp.writeText("Hello","World");
        });
        server.serve("/home", Http.Method.GET ,((req , resp ) -> {
            String name = req.getParam("name");
            int id = Integer.parseInt(req.getParam("id"));
            String client = req.getHeader(HttpRequest.Header.UserAgent);
            resp.writeText("This is your home, " + name + " id:" + id + " from " + client);
        }));

        server.staticResourceDir("D:\\self\\temp\\static");
        server.start();
    }
MIT License Copyright (c) 2021 XieJC Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

简介

Tiny and simple http server in Java without any dependencies 展开 收起
Java
MIT
取消

发行版

暂无发行版

贡献者

全部

近期动态

加载更多
不能加载更多了
Java
1
https://gitee.com/xie-jc/tiny-http-server.git
git@gitee.com:xie-jc/tiny-http-server.git
xie-jc
tiny-http-server
TinyHttpServer
master

搜索帮助