程序员的资源宝库

网站首页 > gitee 正文

hutool发送http请求

sanyeah 2024-04-12 17:40:47 gitee 4 ℃ 0 评论

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);
        }
    

Tags:

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表