package cc.mrbird.febs.unisoftiot.config;
|
|
import cc.mrbird.febs.common.exception.FebsException;
|
import cc.mrbird.febs.unisoftiot.enums.ResponseCodeEnum;
|
import cc.mrbird.febs.unisoftiot.utils.OkHttpUtils;
|
import cn.hutool.core.util.StrUtil;
|
import cn.hutool.json.JSONObject;
|
import okhttp3.Request;
|
import okhttp3.Response;
|
import okhttp3.ResponseBody;
|
import org.json.JSONException;
|
|
import java.io.IOException;
|
|
/**
|
* 响应处理器类,用于处理OKHTTP请求的响应
|
*/
|
public final class ResponseHandler {
|
|
// 错误信息前缀
|
private static final String ERROR_PREFIX = "[ResponseHandler] OKHTTP Error: ";
|
|
// 私有构造方法,防止实例化
|
private ResponseHandler() {
|
}
|
|
/**
|
* 处理HTTP响应
|
* @param request 请求对象
|
* @return 响应体字符串
|
* @throws FebsException 当响应处理失败时抛出
|
*/
|
public static String handleResponse(Request request) {
|
try (
|
// 执行HTTP请求并获取响应
|
Response response = OkHttpUtils.builder().okHttpClient.newCall(request).execute()
|
) {
|
// 获取响应体内容
|
String responseBodyStr = getResponseBodyAsString(response.body());
|
if (ResponseCodeEnum.isFail(response.code())) {
|
throw new FebsException(ERROR_PREFIX + responseBodyStr);
|
}
|
// 如果响应内容为空,则抛出异常
|
if(StrUtil.isEmpty(responseBodyStr)){
|
throw new FebsException(ERROR_PREFIX + "请求返回参数为空");
|
}
|
// 解析响应内容为JSON对象
|
JSONObject jsonObject = new JSONObject(responseBodyStr);
|
// 获取响应码
|
int code = jsonObject.getInt("code");
|
// 如果响应码表示失败,则处理错误响应
|
if(ResponseCodeEnum.isFail(code)){
|
throw handleErrorResponse(code, responseBodyStr);
|
}
|
// 获取响应消息
|
String msg = jsonObject.getStr("msg");
|
// 如果响应消息不正确,则抛出异常
|
if(!ResponseCodeEnum.SUCCESS.getMsg().equals(msg)){
|
throw new FebsException(ERROR_PREFIX + "请求返回参数msg不正确");
|
}
|
// 返回响应内容
|
return responseBodyStr;
|
} catch (IOException | IllegalStateException | JSONException e) {
|
// 捕获异常并抛出自定义异常
|
throw new FebsException(ERROR_PREFIX + e.getMessage());
|
}
|
}
|
|
/**
|
* 处理错误响应
|
* @param code 响应码
|
* @param responseBodyStr 响应体字符串
|
* @return 自定义异常
|
* @throws JSONException 当JSON解析失败时抛出
|
*/
|
private static FebsException handleErrorResponse(int code, String responseBodyStr) {
|
try {
|
// 获取错误描述和消息
|
String desc = ResponseCodeEnum.getDesc(code);
|
String msg = ResponseCodeEnum.getMsg(code);
|
// 构造并返回自定义异常
|
return new FebsException(ERROR_PREFIX + "{" + msg + "},{" + desc + "}");
|
} catch (JSONException e) {
|
// 如果JSON解析失败,构造并返回自定义异常
|
throw new FebsException(ERROR_PREFIX + "{" + responseBodyStr + "}");
|
}
|
}
|
|
/**
|
* 获取响应体内容作为字符串
|
* @param body 响应体
|
* @return 响应体字符串
|
* @throws IOException 当读取响应体失败时抛出
|
*/
|
private static String getResponseBodyAsString(ResponseBody body) throws IOException {
|
if (body != null) {
|
// 如果响应体不为空,读取并返回内容
|
return body.string();
|
} else {
|
// 如果响应体为空,返回空字符串
|
return "";
|
}
|
}
|
}
|