hutool发送http请求

hutool发送http请求

环境 SpringBoot+Maven

  1. 在Maven中导入hutool工具包和junit单元测试包

    <!--hutool工具包-->
    <dependency>
    	<groupId>cn.hutool</groupId>
    	<artifactId>hutool-all</artifactId>
    	<version>5.7.5</version>
    </dependency>
    <!--junit单元测试包-->
    <dependency>
    	<groupId>junit</groupId>
    	<artifactId>junit</artifactId>
    	<version>4.13.2</version>
    	<scope>test</scope>
    </dependency>
    
  2. 新建测试类通过form-data传参方式

    	@Test
        public void sc(){
            JSONObject jsonObject = new JSONObject();
            jsonObject.set("projectNo","123");
            jsonObject.set("projectName","测试");
            //HttpRequest后面可以用get,post,put,delete请求
            String body = HttpRequest.put("http://localhost:8777/**/**")
                    .form(jsonObject)
                	//指定Content-Type类型为multipart/form-data
                    .header("Content-Type","multipart/form-data;charset=UTF-8")
                    .execute()
                    .body();
            System.out.println(body);
        }
    
  3. 新建测试类通过json传参方式

     @Test
        public void sc(){
            //实体类
            User user = new User();
            user.setId("123");
            user.setName("测试");
            String body = HttpRequest.put("http://localhost:8777/**/**")
                	//将实体类转换成json
                    .body(new Gson().toJson(user))
                	//指定Content-Type类型为application/json
                    .header("Content-Type","application/json;charset=UTF-8")
                    .execute()
                    .body();
            System.out.println(body);
        }
    
posted @ 2022-11-28 22:16  striver-sc  阅读(289)  评论(0编辑  收藏  举报