使用hutool封装http请求
目录
使用hutool封装http请求
今天写代码的时候,发现需要使用后台进行http请求的时候,发现自己没有一个请求的封装,这就很不好了,于是乎就要一劳永逸自己写一个工具类进行调用,话不多说开干!
1.首先引入pom
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!--JSON--> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>${fastjson.version}</version> </dependency> <!-- hutool工具 --> <dependency> <groupId>cn.hutool</groupId> <artifactId>hutool-all</artifactId> <version>5.8.9</version> </dependency>
2.封装返回处理
比较简单的写了一下,使用自己项目里的就可以
public enum ResultCode {
/* 成功 */
SUCCESS(200, "成功"),
/* 默认失败 */
COMMON_FAIL(999, "失败"),
/* 参数错误:1000~1999 */
PARAM_NOT_VALID(1001, "参数无效"),
PARAM_IS_BLANK(1002, "参数为空"),
PARAM_TYPE_ERROR(1003, "参数类型错误"),
PARAM_NOT_COMPLETE(1004, "参数缺失"),
/* 业务错误 */
NO_PERMISSION(3001, "没有权限");
private Integer code;
private String message;
ResultCode(Integer code, String message) {
this.code = code;
this.message = message;
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
/**
* 根据code获取message
*
* @param code
* @return
*/
public static String getMessageByCode(Integer code) {
for (ResultCode ele : values()) {
if (ele.getCode().equals(code)) {
return ele.getMessage();
}
}
return null;
}
}
/**
* @Author: zm
* @Description: 统一返回实体
* @Date: 2022/4/24 8:51
*/
public class JsonResult<T> implements Serializable {
private Boolean success;
private Integer errorCode;
private String errorMsg;
private T data;
public JsonResult() {
}
public JsonResult(boolean success) {
this.success = success;
this.errorCode = success ? ResultCode.SUCCESS.getCode() : ResultCode.COMMON_FAIL.getCode();
this.errorMsg = success ? ResultCode.SUCCESS.getMessage() : ResultCode.COMMON_FAIL.getMessage();
}
public JsonResult(boolean success, ResultCode resultEnum) {
this.success = success;
this.errorCode = success ? ResultCode.SUCCESS.getCode() : (resultEnum == null ? ResultCode.COMMON_FAIL.getCode() : resultEnum.getCode());
this.errorMsg = success ? ResultCode.SUCCESS.getMessage() : (resultEnum == null ? ResultCode.COMMON_FAIL.getMessage() : resultEnum.getMessage());
}
public JsonResult(boolean success, T data) {
this.success = success;
this.errorCode = success ? ResultCode.SUCCESS.getCode() : ResultCode.COMMON_FAIL.getCode();
this.errorMsg = success ? ResultCode.SUCCESS.getMessage() : ResultCode.COMMON_FAIL.getMessage();
this.data = data;
}
public JsonResult(boolean success, ResultCode resultEnum, T data) {
this.success = success;
this.errorCode = success ? ResultCode.SUCCESS.getCode() : (resultEnum == null ? ResultCode.COMMON_FAIL.getCode() : resultEnum.getCode());
this.errorMsg = success ? ResultCode.SUCCESS.getMessage() : (resultEnum == null ? ResultCode.COMMON_FAIL.getMessage() : resultEnum.getMessage());
this.data = data;
}
public Boolean getSuccess() {
return success;
}
public void setSuccess(Boolean success) {
this.success = success;
}
public Integer getErrorCode() {
return errorCode;
}
public void setErrorCode(Integer errorCode) {
this.errorCode = errorCode;
}
public String getErrorMsg() {
return errorMsg;
}
public void setErrorMsg(String errorMsg) {
this.errorMsg = errorMsg;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
}
public class ResultTool {
public static <T> JsonResult<T> success() {
return new JsonResult<T>(true);
}
public static <T> JsonResult<T> success(T data) {
return new JsonResult<T>(true, data);
}
public static <T> JsonResult<T> fail() {
return new JsonResult<T>(false);
}
public static <T> JsonResult<T> fail(ResultCode resultEnum) {
return new JsonResult<T>(false, resultEnum);
}
public static <T> JsonResult<T> fail(boolean success,T data) {
return new JsonResult<T>(false, data);
}
}
3.封装http请求
我们基于hutool的HttpRequest请求进行自己代码的封装
package com.zm.test.utils;
import cn.hutool.core.map.MapUtil;
import cn.hutool.http.*;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zm.test.commons.result.JsonResult;
import com.zm.test.commons.result.ResultTool;
import lombok.extern.slf4j.Slf4j;
import java.util.HashMap;
import java.util.Map;
/**
* http请求处理
* 默认json格式请求
* @author zm
* @date 2025/3/7
*/
@Slf4j
public class HttpUtils {
private static final Map<String,String> initHeaderMap= new HashMap<>();
static {
initHeaderMap.put(Header.CONTENT_TYPE.getValue(), ContentType.JSON.getValue());
}
/**
* get请求
* @param url 路径
* @param clazz 返回实体
* @param <T> 自定义实体
* @return T
*/
public static <T> JsonResult<T> httpGet(String url, Class<T> clazz){
try{
HttpResponse getResponse=HttpRequest.get(url)
.headerMap(initHeaderMap,false)
.execute();
String body=getResponse.body();
if(getResponse.isOk()){
return ResultTool.success(JSONObject.parseObject(body, clazz));
}
log.info("GET请求错误:返回状态码:{},返回信息:{}",getResponse.getStatus(),body);
return ResultTool.fail(false,JSONObject.parseObject(body, clazz));
}catch (HttpException e){
log.error("GET请求失败:{}",e.getMessage());
return ResultTool.fail();
}
}
/**
* get请求
* @param url 路径
* @param param 请求参数
* @param clazz 返回实体
* @param <T> 自定义实体
* @return T
*/
public static <T> JsonResult<T> httpGet(String url, Map<String,Object> param,Class<T> clazz){
try{
HttpResponse getResponse=HttpRequest.get(url)
.headerMap(initHeaderMap,false)
.form(param)
.execute();
String body=getResponse.body();
if(getResponse.isOk()){
return ResultTool.success(JSONObject.parseObject(body, clazz));
}
log.info("GET请求错误:返回状态码:{},返回信息:{}",getResponse.getStatus(),body);
return ResultTool.fail(false,JSONObject.parseObject(body, clazz));
}catch (HttpException e){
log.error("GET请求失败:{}",e.getMessage());
return ResultTool.fail();
}
}
/**
* get请求自定义header
* @param url 路径
* @param param 请求参数
* @param header 请求头
* @param clazz 返回实体
* @param <T> 自定义实体
* @return T
*/
public static <T> JsonResult<T> httpGet(String url,Map<String,Object> param,Map<String,String> header, Class<T> clazz){
try{
HttpResponse getResponse=HttpRequest.get(url)
.headerMap(MapUtil.isEmpty(header)?initHeaderMap:header,false)
.form(param)
.execute();
String body=getResponse.body();
if(getResponse.isOk()){
return ResultTool.success(JSONObject.parseObject(body, clazz));
}
log.info("GET请求错误:返回状态码:{},返回信息:{}",getResponse.getStatus(),body);
return ResultTool.fail(false,JSONObject.parseObject(body, clazz));
}catch (HttpException e){
log.error("GET请求失败:{}",e.getMessage());
return ResultTool.fail();
}
}
/**
* post请求
* @param url 路径
* @param clazz 返回实体
* @param <T> 自定义实体
* @return T
*/
public static <T> JsonResult<T> httpPost(String url,Map<String,Object> param, Class<T> clazz){
try{
HttpResponse getResponse=HttpRequest.post(url)
.headerMap(initHeaderMap,false)
.form(param)
.execute();
String body=getResponse.body();
if(getResponse.isOk()){
return ResultTool.success(JSONObject.parseObject(body, clazz));
}
log.info("POST请求错误:返回状态码:{},返回信息:{}",getResponse.getStatus(),body);
return ResultTool.fail(false,JSONObject.parseObject(body, clazz));
}catch (HttpException e){
log.error("POST请求失败:{}",e.getMessage());
return ResultTool.fail();
}
}
/**
* post请求
* @param url 路径
* @param header 请求头
* @param clazz 返回实体
* @param <T> 自定义实体
* @return T
*/
public static <T> JsonResult<T> httpPost(String url,Map<String,Object> param,Map<String,String> header, Class<T> clazz){
try{
HttpResponse getResponse=HttpRequest.post(url)
.headerMap(MapUtil.isEmpty(header)?initHeaderMap:header,false)
.form(param)
.execute();
String body=getResponse.body();
if(getResponse.isOk()){
return ResultTool.success(JSONObject.parseObject(body, clazz));
}
log.info("POST请求错误:返回状态码:{},返回信息:{}",getResponse.getStatus(),body);
return ResultTool.fail(false,JSONObject.parseObject(body, clazz));
}catch (HttpException e){
log.error("POST请求失败:{}",e.getMessage());
return ResultTool.fail();
}
}
/**
* post请求
* @param url 路径
* @param param 请求传参
* @param clazz 返回实体
* @param <T> 自定义实体
* @return T
*/
public static <T,E> JsonResult<T> httpPost(String url,E param, Class<T> clazz){
try{
HttpResponse getResponse=HttpRequest.post(url)
.headerMap(initHeaderMap,false)
.body(JSON.toJSONString(param))
.execute();
String body=getResponse.body();
if(getResponse.isOk()){
return ResultTool.success(JSONObject.parseObject(body, clazz));
}
log.info("POST请求错误:返回状态码:{},返回信息:{}",getResponse.getStatus(),body);
return ResultTool.fail(false,JSONObject.parseObject(body, clazz));
}catch (HttpException e){
log.error("POST请求失败:{}",e.getMessage());
return ResultTool.fail();
}
}
/**
* post请求
* @param url 路径
* @param param 请求传参
* @param header 请求头
* @param clazz 返回实体
* @param <T> 自定义实体
* @return T
*/
public static <T,E> JsonResult<T> httpPost(String url,E param,Map<String,String> header, Class<T> clazz){
try{
HttpResponse getResponse=HttpRequest.post(url)
.headerMap(MapUtil.isEmpty(header)?initHeaderMap:header,false)
.body(JSON.toJSONString(param))
.execute();
String body=getResponse.body();
if(getResponse.isOk()){
return ResultTool.success(JSONObject.parseObject(body, clazz));
}
log.info("POST请求错误:返回状态码:{},返回信息:{}",getResponse.getStatus(),body);
return ResultTool.fail(false,JSONObject.parseObject(body, clazz));
}catch (HttpException e){
log.error("POST请求失败:{}",e.getMessage());
return ResultTool.fail();
}
}
}
完成收工!!!