KKSU
2024-11-15 2147ca2f66dd5ff83db5080988f4832bd10ac213
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
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());
        }
    }
 
 
}