10【hutool】hutool-http

961 阅读1分钟

该系列文章主要是对 hutool 工具类的介绍,详情可以参考

hutool.cn/docs/#/

Hutool-http针对JDK的HttpUrlConnection做一层封装,简化了HTTPS请求、文件上传、Cookie记忆等操作,使Http请求变得无比简单。

  • Hutool-http的核心集中在两个类:
    • HttpRequest
    • HttpResponse

同时针对大部分情境,封装了HttpUtil工具类。

1 get 请求

    @Test
    public void getTest() {
        Map<String, String> headers = new HashMap<>();
        headers.put("key1", "value1");
        HttpResponse resp = HttpRequest
                .get("http://172.22.12.13:8088/get?id=1")
                .addHeaders(headers)
                .body("{\"test\":\"test\"}")
                .execute();
        Console.log(resp.body());
    }

2 post 请求

    @Test
    public void postTest() {
        Map<String, String> headers = new HashMap<>();
        headers.put("key1", "value1");
        HttpResponse resp = HttpRequest
                .post("http://172.22.12.13:8088/post?id=1")
                .addHeaders(headers)
                .body("{\"test\":\"test\"}")
                .execute();
        Console.log(resp.body());
    }

3 搭建一个简单的 http 服务端

    @Test
    public void serverTest() {
        HttpUtil.createServer(8888)
                .addFilter(((req, res, chain) -> {
                    Console.log("Filter: " + req.getPath());
                    chain.doFilter(req.getHttpExchange());
                }))
                // get数据测试,返回请求的PATH
                .addAction("/get", (request, response) ->
                        response.write(request.getURI().toString(), ContentType.TEXT_PLAIN.toString())
                )
                // 返回JSON数据测试
                .addAction("/restTest", (request, response) -> {
                    String res = JSONUtil.createObj()
                            .set("id", 1)
                            .set("method", request.getMethod())
                            .set("request", request.getBody())
                            .toStringPretty();
                    response.write(res, ContentType.JSON.toString());
                })
                // 获取表单数据测试
                // http://localhost:8888/formTest?a=1&a=2&b=3
                .addAction("/formTest", (request, response) ->
                        response.write(request.getParams().toString(), ContentType.TEXT_PLAIN.toString())
                )

                // 文件上传测试
                // http://localhost:8888/formForUpload.html
                .addAction("/file", (request, response) -> {
                            Console.log("Upload file...");
                            Console.log(request.getParams());
                            final UploadFile[] files = request.getMultipart().getFiles("file");
                            // 传入目录,默认读取HTTP头中的文件名然后创建文件
                            for (UploadFile file : files) {
                                file.write("d:/test/");
                                Console.log("Write file: d:/test/" + file.getFileName());
                            }
                            response.write(request.getMultipart().getParamMap().toString(), ContentType.TEXT_PLAIN.toString());
                        }
                )
                .start();
        while (true) {
        }
    }