package cc.mrbird.febs.unisoftiot.config;
|
|
import cc.mrbird.febs.common.exception.FebsException;
|
import cc.mrbird.febs.unisoftiot.enums.HttpMethod;
|
import okhttp3.MediaType;
|
import okhttp3.Request;
|
import okhttp3.RequestBody;
|
|
/**
|
* 请求构建器类,用于构建HTTP请求
|
*/
|
public final class RequestBuilder {
|
|
// 定义JSON类型的媒体类型常量
|
private static final MediaType JSON_TYPE = MediaType.parse("application/json; charset=utf-8");
|
|
// 私有构造方法,防止实例化
|
private RequestBuilder() {
|
}
|
|
/**
|
* 根据提供的参数构建HTTP请求
|
*
|
* @param fullUrl 完整的请求URL
|
* @param body 请求体内容
|
* @param httpMethod HTTP方法枚举类型
|
* @return 构建好的Request对象
|
* @throws FebsException 如果URL无效或HTTP方法不支持,则抛出此异常
|
*/
|
public static Request buildRequest(String fullUrl, String body, HttpMethod httpMethod) {
|
// 校验 URL
|
if (fullUrl == null || fullUrl.isEmpty()) {
|
throw new FebsException("Invalid URL: URL cannot be null or empty");
|
}
|
|
// 创建Request.Builder对象用于配置请求
|
Request.Builder builder = new Request.Builder();
|
try {
|
// 根据HTTP方法构建不同的请求
|
final Request request;
|
switch (httpMethod) {
|
case POST:
|
// 构建POST请求,并设置请求体为JSON类型
|
request = builder
|
.url(fullUrl)
|
.post(RequestBody.create(JSON_TYPE, body))
|
.addHeader("X-APISpace-Token","")
|
.addHeader("Content-Type","")
|
.build();
|
break;
|
case GET:
|
// 构建GET请求
|
request = builder
|
.url(fullUrl)
|
.get()
|
.addHeader("Content-Type", "application/x-www-form-urlencoded")
|
.build();
|
break;
|
default:
|
// 如果HTTP方法不支持,抛出异常
|
throw new FebsException("Invalid HTTP method: " + httpMethod);
|
}
|
// 返回构建好的请求对象
|
return request;
|
} catch (IllegalArgumentException e) {
|
// 如果URL格式错误,抛出异常
|
throw new FebsException("Invalid URL: " + e.getMessage());
|
}
|
}
|
|
|
}
|