首先引入jar包
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.8.10</version>
</dependency>
post
/**
* post请求
* @param json
* @param url
* @return
*/
public static HttpResponse post(String json, String url,String token){
// 添加请求头信息
Map<String, String > heads = new HashMap<>(10);
// 使用json发送请求,下面的是必须的
heads.put("Content-Type", "application/json;charset=UTF-8");
heads.put("Authorization", "Bearer "+token);
/**
** headerMap是添加的请求头,
body是传入的参数,这里选择json,后端使用@RequestBody接收
*/
HttpResponse response = null;
try {
response = HttpRequest.post(url)
.headerMap(heads, false)
.body(json)
.timeout(20000)
.execute();
//有个坑超过21秒会导致失效,注意
} catch (Exception e) {
log.error("url请求失败:{}", url,e.getMessage());
response = null;
}
return response;
}
get
/**
* get请求
* @param url
* @return
*/
public static HttpResponse get(String url){
HttpResponse response = null;
try {
response = HttpRequest.get(url).timeout(20000)
.header("Content-Type", "application/json").execute();
}catch (Exception e) {
log.error("url请求失败:{}", url,e.getMessage());
response = null;
}
return response;
}
然后就是针对HttpResponse
解析
String res = response.body();
******
pom文件
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.8.10</version>
</dependency>