基于hutool包下的httpUtil类实现项目之间调用get和post请求
1,首先导入依赖
<!-- httpclient缓存 -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient-cache</artifactId>
<version>4.5</version>
</dependency>
<!-- http的mime类型都在这里面 -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.3.2</version>
</dependency>
2,测试类实现get请求
//获取用户信息
@Test
public void test3(){
//发送get请求
String getResult = HttpUtil.createGet("http://127.0.0.1:8080//api/user/id/3")
//这个请求头.header是自己项目需要加的,可以省略
.header("Authorzation","Basic dG9uZ2Z1bNsb3VkX3VpOnRvbmdmdW5jbG91ZF91aV9zZWNyZXQ=")
.execute()
//返回参数格式utf-8
.charset("utf-8")
.body();
log.info("get结果打印:{}",getResult);
}
3、测试类实现post请求
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.time.DateFormatUtils;
import org.junit.jupiter.api.Test;
import cn.hutool.http.HttpRequest;
//使用用户名、密码、验证码进行登陆
@Test
public void test2(){
//设置请求参数
JSONObject jsonObject = JSONUtil.createObj();
jsonObject.put("account","admin");
jsonObject.put("code","");
jsonObject.put("grantType","password");
jsonObject.put("key","");
jsonObject.put("password","12345");
jsonObject.put("refreshToken","");
jsonObject.put("tenant","MD");
//发送post请求
String postResult = HttpRequest.post("http://127.0.0.1:8080/api/token")
//设置请求头
.header("Content-Type","application/json")
//这两个请求头是项目需要加的,可以省略
.header("Authorization","Basic dG9u1ZF91aV9zZWNyZXQ=")
.header("tenant","MD")
//传输参数
.body(jsonObject.toString())
.execute()
.body();
log.info("post结果打印{}",postResult);
}