package cc.mrbird.febs.unisoftiot.config;
|
|
import cc.mrbird.febs.common.exception.FebsException;
|
import cc.mrbird.febs.unisoftiot.enums.HttpMethod;
|
import cc.mrbird.febs.unisoftiot.utils.UrlUtils;
|
import cn.hutool.json.JSONUtil;
|
import com.alibaba.fastjson.JSON;
|
import lombok.extern.slf4j.Slf4j;
|
import okhttp3.Request;
|
|
import java.util.LinkedHashMap;
|
|
/**
|
* 请求处理器类,用于构建和发送API请求
|
*/
|
@Slf4j
|
public class RequestHandler {
|
|
private String appId;
|
private String appSecret;
|
|
/**
|
* 构造函数,初始化appId和appSecret
|
*
|
* @param appId 应用ID
|
* @param appSecret 应用密钥
|
*/
|
public RequestHandler(String appId,String appSecret){
|
this.appId = appId;
|
this.appSecret = appSecret;
|
}
|
|
/**
|
* 发送API请求
|
*
|
* @param baseUrl 基础URL
|
* @param urlPath URL路径
|
* @param parameters 请求参数
|
* @param httpMethod HTTP方法
|
* @return 请求结果字符串
|
* @throws FebsException 当HTTP方法不支持时抛出异常
|
*/
|
private String sendApiRequest(String baseUrl,
|
String urlPath,
|
LinkedHashMap<String, Object> parametersw,
|
HttpMethod httpMethod) {
|
|
// 创建参数集合,用于设备控制
|
LinkedHashMap<String, Object> parameters = new LinkedHashMap<>();
|
// 添加控制设备的参数,这里的例子是开启设备的某个功能
|
parameters.put("device", "1438");
|
parameters.put("power3", "1");
|
log.info("parameters",parameters.toString());
|
String fullUrl = "";
|
Request request;
|
// 根据HTTP方法构建请求
|
switch (httpMethod) {
|
case POST:
|
// 对于POST请求,将参数序列化为JSON体
|
fullUrl = UrlUtils.getUrl(baseUrl,appId,appSecret,urlPath,null);
|
String body = JSON.toJSONString(parameters);
|
log.info("parametersJson:", JSONUtil.parseObj(parameters));
|
log.info("body:",body);
|
request = RequestBuilder.buildRequest(fullUrl, body,httpMethod);
|
break;
|
case GET:
|
// 对于GET请求,将参数直接拼接到URL中
|
fullUrl = UrlUtils.getUrl(baseUrl,appId,appSecret,urlPath,parameters);
|
request = RequestBuilder.buildRequest(fullUrl, null,httpMethod);
|
break;
|
default:
|
// 不支持的HTTP方法抛出异常
|
throw new FebsException("[RequestHandler] HttpMethod 不支持: " + httpMethod);
|
}
|
|
// 记录请求信息
|
log.info("{} {}", httpMethod, fullUrl);
|
|
// 发送请求并处理响应
|
return ResponseHandler.handleResponse(request);
|
}
|
|
/**
|
* 发送签名请求,确保appId和appSecret不为空
|
*
|
* @param baseUrl 基础URL
|
* @param urlPath URL路径
|
* @param parameters 请求参数
|
* @param httpMethod HTTP方法
|
* @return 请求结果字符串
|
* @throws FebsException 当appId或appSecret为空时抛出异常
|
*/
|
public String sendSignedRequest(String baseUrl,
|
String urlPath,
|
LinkedHashMap<String, Object> parameters,
|
HttpMethod httpMethod) {
|
// 校验appId和appSecret
|
if (null == appId || appId.isEmpty() || null == appSecret || appSecret.isEmpty()) {
|
throw new FebsException("[RequestHandler] appId/appSecret 不能为空!");
|
}
|
// 调用sendApiRequest方法发送请求
|
return sendApiRequest(baseUrl, urlPath, parameters, httpMethod);
|
}
|
|
}
|