hutool工具类的post请求不同类型参数的接口

  • Post author:
  • Post category:其他


hutool:5.0.5

接口测试都是这个文章的测试接口

springBoot下的post接口_震旦小读者的博客-CSDN博客

一、表单提交方式(@RequestParam修饰的参数)

//        Map<String, Object> param = new HashMap<>();
        JSONObject param = JSONUtil.createObj();
        param.put("name", "test");
        param.put("age", 10);
        String result = HttpUtil.post(url + "/testForm", param);
        System.out.println(JSONUtil.parseObj(result));
{"msg":"操作成功","code":"200","data":{"name":"test","age":10}}

使用的参数map或者jsonObject都可以成功调用

二、@RequestBody修饰json对象参数

        JSONObject param = JSONUtil.createObj();
        param.put("name", "test");
        param.put("age", 10);
        String result = HttpUtil.post(url + "/testJsonBody", param.toString());
        System.out.println(JSONUtil.parseObj(result));
{"msg":"操作成功","code":"200","data":{"name":"test","age":10}}

参数只能使用JSONObject格式的,不能使用Map之类的,否则格式不对无法调用接口。

三、@RequestBody修饰json格式字符串参数

        JSONObject param = JSONUtil.createObj();
        param.put("name", "test");
        param.put("age", 10);
        String result = HttpUtil.post(url + "/testJsonStr", param.toString());
        System.out.println(JSONUtil.parseObj(result));
{"msg":"操作成功","code":"200","data":{"name":"test","age":10}}

参数只能使用JSONObject格式的,不能使用Map之类的,map转换为json格式的时候是用=号的,而不是:号。

四、自定义post请求

        JSONObject param = JSONUtil.createObj();
        param.put("name", "test");
        param.put("age", 10);
        HttpRequest.post(url + "/testJsonStr").header("abc", "abc").body(param.toString()).execute().body();
        String result = HttpUtil.post(url + "/testJsonStr", param.toString());
        System.out.println(JSONUtil.parseObj(result));
{"msg":"操作成功","code":"200","data":{"name":"test","age":10}}

五、更多用法可以查阅官方文档

Hutool参考文档



版权声明:本文为RX_780原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。