吉安感知网项目-后端
linwei
2026-02-06 e9a12776ee053cdf4a682f972e2fd830ebbab88c
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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
package org.sxkj.common.utils;
 
import com.alibaba.cloud.commons.lang.StringUtils;
import org.hsqldb.lib.StringUtil;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.sxkj.common.constant.CommonConstant;
 
import javax.servlet.http.HttpServletRequest;
import java.util.*;
 
/**
 * HTTP 请求头工具类
 */
public class HeaderUtils {
 
 
    /**
     * 从当前请求中获取指定请求头(适用于Spring MVC环境)
     *
     * @param headerName 请求头名称(不区分大小写)
     * @return 请求头值,不存在返回Optional.empty()
     */
    public static Optional<String> getHeader(String headerName) {
        return Optional.ofNullable(getServletRequest())
            .flatMap(request -> getHeader(request, headerName));
    }
 
    /**
     * 获取头信息中的城市code
     *
     * @return
     */
    public static String getAreaCode() {
        return getAreaCode(null);
 
    }
 
    /**
     * * 获取城市code,没有传参按头信息中的
     *
     * @param areaCodeParam 待截取的行政区划
     * @return 截取之后的行政区划code
     */
    public static String getAreaCode(String areaCodeParam) {
        return getAreaCodeHeaderAreaCode(areaCodeParam);
    }
 
    /**
     * 格式化区域数据  360000 将后面的0000去掉
     *
     * @param areaCode 区域
     * @return 后面无0 的数据
     */
    public static String formatAreaCode(String areaCode) {
        if (StringUtils.isEmpty(areaCode)) {
            return areaCode;
        }
        areaCode = areaCode.replaceAll("0+$", "");
        if (areaCode.length() % 2 == 1) {
            return areaCode + "0";
        }
        return areaCode;
    }
 
 
    /**
     * 获取行政区划,不删除长度
     *
     * @param areaCodeParam 行政区划 优先返回
     * @return 行政区划
     */
    public static String getAreaCodeHeaderAreaCode(String areaCodeParam) {
        String areaCode = getHeader(CommonConstant.AREA_CODE).orElse(null);
        String code = StringUtils.isEmpty(areaCodeParam) ? areaCode : areaCodeParam;
        return formatAreaCode(code);
    }
 
    /**
     * 获取行政区划,不处理长度
     * @param areaCodeParam 行政区划 优先返回
     * @return 行政区划code
     */
    public static String getAreaCodeHeaderAreaCodeNot(String areaCodeParam) {
        String areaCode = getHeader(CommonConstant.AREA_CODE).orElse(null);
        return StringUtils.isEmpty(areaCodeParam) ? areaCode : areaCodeParam;
    }
 
 
    /**
     * 从HttpServletRequest中获取指定请求头
     *
     * @param request    HttpServletRequest对象
     * @param headerName 请求头名称(不区分大小写)
     * @return 请求头值,不存在返回Optional.empty()
     */
    public static Optional<String> getHeader(HttpServletRequest request, String headerName) {
        if (request == null || headerName == null || headerName.isEmpty()) {
            return Optional.empty();
        }
 
        // 先尝试直接获取(性能更优)
        String value = request.getHeader(headerName);
        if (value != null) {
            return Optional.of(value);
        }
 
        // 如果直接获取不到,再遍历所有header进行不区分大小写的匹配
        Enumeration<String> headerNames = request.getHeaderNames();
        while (headerNames != null && headerNames.hasMoreElements()) {
            String name = headerNames.nextElement();
            if (headerName.equalsIgnoreCase(name)) {
                return Optional.ofNullable(request.getHeader(name));
            }
        }
 
        return Optional.empty();
    }
 
    /**
     * 从ServerHttpRequest中获取指定请求头(适用于WebFlux环境)
     *
     * @param request    ServerHttpRequest对象
     * @param headerName 请求头名称(不区分大小写)
     * @return 请求头值,不存在返回Optional.empty()
     */
    public static Optional<String> getHeader(ServerHttpRequest request, String headerName) {
        if (request == null || headerName == null || headerName.isEmpty()) {
            return Optional.empty();
        }
 
        HttpHeaders headers = request.getHeaders();
        // 先尝试直接获取(性能更优)
        if (headers.containsKey(headerName)) {
            return Optional.ofNullable(headers.getFirst(headerName));
        }
 
        // 如果直接获取不到,再遍历所有header进行不区分大小写的匹配
        for (Map.Entry<String, List<String>> entry : headers.entrySet()) {
            if (headerName.equalsIgnoreCase(entry.getKey())) {
                return Optional.ofNullable(entry.getValue().get(0));
            }
        }
 
        return Optional.empty();
    }
 
    /**
     * 获取当前请求的所有请求头(适用于Spring MVC环境)
     *
     * @return 请求头Map,键已转为小写
     */
    public static Map<String, String> getAllHeaders() {
        return Optional.ofNullable(getServletRequest())
            .map(HeaderUtils::getAllHeaders)
            .orElse(Collections.emptyMap());
    }
 
    /**
     * 从HttpServletRequest获取所有请求头
     *
     * @param request HttpServletRequest对象
     * @return 请求头Map,键已转为小写
     */
    public static Map<String, String> getAllHeaders(HttpServletRequest request) {
        Map<String, String> headers = new HashMap<>();
        if (request != null) {
            Enumeration<String> headerNames = request.getHeaderNames();
            while (headerNames != null && headerNames.hasMoreElements()) {
                String name = headerNames.nextElement();
                headers.put(name.toLowerCase(), request.getHeader(name));
            }
        }
        return headers;
    }
 
    /**
     * 从ServerHttpRequest获取所有请求头(适用于WebFlux环境)
     *
     * @param request ServerHttpRequest对象
     * @return 请求头Map,键已转为小写
     */
    public static Map<String, String> getAllHeaders(ServerHttpRequest request) {
        Map<String, String> headers = new HashMap<>();
        if (request != null) {
            request.getHeaders().forEach((key, values) ->
                headers.put(key.toLowerCase(), values.get(0)));
        }
        return headers;
    }
 
    /**
     * 处理区域代码,提取最后一组并补零到12位
     *
     * @param areaCode 原始区域代码,可能包含多个以逗号分隔的代码
     * @return 处理后的区域代码,补零到12位
     */
    public static String processAreaCode(String areaCode) {
        if (areaCode != null && !areaCode.isEmpty()) {
            // 分割区域代码并只取最后一组
            String[] codes = areaCode.split(",");
            if (codes.length > 0) {
                // 取最后一组并去除空格
                String lastCode = codes[codes.length - 1].trim();
                if (!lastCode.isEmpty()) {
                    // 补零到12位
                    return lastCode + "000000000000".substring(lastCode.length());
                }
            }
        }
        return areaCode;
    }
 
    /**
     * 获取当前HttpServletRequest对象
     *
     * @return HttpServletRequest对象,可能为null
     */
    private static HttpServletRequest getServletRequest() {
        try {
            ServletRequestAttributes attributes = (ServletRequestAttributes)
                RequestContextHolder.getRequestAttributes();
            return attributes != null ? attributes.getRequest() : null;
        } catch (IllegalStateException e) {
            // 非Web请求上下文
            return null;
        }
    }
}