月球大数据地理空间分析展示平台-【后端】-月球后台服务
13693261870
2023-09-27 aa4429a11d9b73bbcb1628090b6bafb75c4c6a00
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
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
package com.moon.server.helper;
 
import com.moon.server.entity.all.StaticData;
import com.moon.server.entity.sys.ResEntity;
import org.apache.http.*;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.utils.URIUtils;
import org.apache.http.entity.InputStreamEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicHttpEntityEnclosingRequest;
import org.apache.http.message.BasicHttpRequest;
import org.apache.http.message.HeaderGroup;
import org.apache.http.util.EntityUtils;
 
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.HttpCookie;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
import java.util.Enumeration;
 
/**
 * Http帮助类
 * @author WWW
 */
public class HttpHelper {
    private final static String HTTP_SLASH2 = "://";
 
    private final static String HTTP_SLASH = "/";
 
    private final static Integer THREE = 3;
 
    protected static final HeaderGroup HOP_HEADERS;
 
    static {
        HOP_HEADERS = new HeaderGroup();
 
        String[] headers = new String[]{
                "Connection", "Keep-Alive", "Proxy-Authenticate", "Proxy-Authorization",
                "TE", "Trailers", "Transfer-Encoding", "Upgrade",
                //"X-RateLimit-Burst-Capacity", "X-RateLimit-Remaining", "X-RateLimit-Replenish-Rate",
                "Access-Control-Allow-Origin", "Access-Control-Allow-Credentials", "Access-Control-Allow-Headers"};
 
        for (String header : headers) {
            HOP_HEADERS.addHeader(new BasicHeader(header, null));
        }
    }
 
    public void service(HttpServletRequest request, HttpServletResponse response, ResEntity entity, String url) throws ServletException, IOException {
        HttpRequest proxyRequest;
        if (request.getHeader(HttpHeaders.CONTENT_LENGTH) != null || request.getHeader(HttpHeaders.TRANSFER_ENCODING) != null) {
            proxyRequest = newProxyRequestWithEntity(request, url);
        } else {
            proxyRequest = new BasicHttpRequest(request.getMethod(), url);
        }
 
        HttpHost host = this.getTargetHost(url);
        // copyRequestHeaders(request, proxyRequest, host);
        //setXrForwardedForHeader(request, proxyRequest);
 
        // if (!StringHelper.isEmpty(cookie)) proxyRequest.addHeader("Cookie", cookie + "; ")
 
        CloseableHttpClient client = null;
        HttpResponse proxyResponse = null;
 
        try {
            client = this.createHttpClient();
            proxyResponse = client.execute(host, proxyRequest);
 
            int statusCode = proxyResponse.getStatusLine().getStatusCode();
            // response.setStatus(statusCode, proxyResponse.getStatusLine().getReasonPhrase())
            response.setStatus(statusCode);
 
            copyResponseHeaders(proxyResponse, request, response, url);
 
            if (statusCode == HttpServletResponse.SC_NOT_MODIFIED) {
                response.setIntHeader(HttpHeaders.CONTENT_LENGTH, 0);
            } else {
                copyResponseEntity(proxyResponse, request, response, entity);
            }
        } catch (Exception ex) {
            throw new ServletException(ex.getMessage());
        } finally {
            if (proxyResponse != null) {
                EntityUtils.consumeQuietly(proxyResponse.getEntity());
            }
            if (client != null) {
                client.close();
            }
        }
    }
 
    protected HttpRequest newProxyRequestWithEntity(HttpServletRequest request, String url) throws IOException {
        String method = request.getMethod();
        HttpEntityEnclosingRequest proxyRequest = new BasicHttpEntityEnclosingRequest(method, url);
        proxyRequest.setEntity(new InputStreamEntity(request.getInputStream(), getContentLength(request)));
        //String str = EntityUtils.toString(proxyRequest.getEntity(), "UTF-8")
 
        return proxyRequest;
    }
 
    private long getContentLength(HttpServletRequest request) {
        String contentLengthHeader = request.getHeader("Content-Length");
        if (contentLengthHeader != null) {
            return Long.parseLong(contentLengthHeader);
        }
 
        return -1L;
    }
 
    protected void copyRequestHeaders(HttpServletRequest request, HttpRequest proxyRequest, HttpHost host) {
        @SuppressWarnings("unchecked")
        Enumeration<String> enumerationOfHeaderNames = request.getHeaderNames();
 
        while (enumerationOfHeaderNames.hasMoreElements()) {
            String headerName = enumerationOfHeaderNames.nextElement();
            copyRequestHeader(request, proxyRequest, host, headerName);
        }
    }
 
    protected void copyRequestHeader(HttpServletRequest request, HttpRequest proxyRequest, HttpHost host, String headerName) {
        if (headerName.equalsIgnoreCase(HttpHeaders.CONTENT_LENGTH) || HOP_HEADERS.containsHeader(headerName)) {
            return;
        }
 
        @SuppressWarnings("unchecked")
        Enumeration<String> headers = request.getHeaders(headerName);
        while (headers.hasMoreElements()) {
            String headerValue = headers.nextElement();
            if (headerName.equalsIgnoreCase(HttpHeaders.HOST)) {
                headerValue = host.getHostName();
                if (host.getPort() != -1) {
                    headerValue += ":" + host.getPort();
                }
            } else if (headerName.equalsIgnoreCase(org.apache.http.cookie.SM.COOKIE)) {
                headerValue = getRealCookie(headerValue);
            }
 
            proxyRequest.addHeader(headerName, headerValue);
        }
    }
 
    protected HttpHost getTargetHost(String url) throws ServletException {
        try {
            URI uri = new URI(url);
 
            return URIUtils.extractHost(uri);
        } catch (URISyntaxException ex) {
            throw new ServletException(ex.getMessage());
        }
    }
 
    protected String getRealCookie(String cookieValue) {
        StringBuilder escapedCookie = new StringBuilder();
 
        String[] cookies = cookieValue.split("[;,]");
        for (String cookie : cookies) {
            String[] cookieSplit = cookie.split("=");
            if (cookieSplit.length == 2) {
                String cookieName = cookieSplit[0].trim();
                if (cookieName.startsWith(cookieName)) {
                    cookieName = cookieName.substring(cookieName.length());
                    if (escapedCookie.length() > 0) {
                        escapedCookie.append("; ");
                    }
                    escapedCookie.append(cookieName).append("=").append(cookieSplit[1].trim());
                }
            }
        }
 
        return escapedCookie.toString();
    }
 
    private void setXrForwardedForHeader(HttpServletRequest request, HttpRequest proxyRequest) {
        String forHeaderName = "X-Forwarded-For";
        String forHeader = request.getRemoteAddr();
        String existingForHeader = request.getHeader(forHeaderName);
        if (existingForHeader != null) {
            forHeader = existingForHeader + ", " + forHeader;
        }
        proxyRequest.setHeader(forHeaderName, forHeader);
 
        String protoHeaderName = "X-Forwarded-Proto";
        String protoHeader = request.getScheme();
        proxyRequest.setHeader(protoHeaderName, protoHeader);
    }
 
    protected CloseableHttpClient createHttpClient() {
        RequestConfig requestConfig = RequestConfig.custom()
                .setRedirectsEnabled(false)
                .setCookieSpec(CookieSpecs.IGNORE_COOKIES)
                .setConnectTimeout(-1)
                .setSocketTimeout(-1)
                .build();
 
        // return HttpClientBuilder.create().setDefaultRequestConfig(requestConfig).build()
        return HttpClients.custom()
                .setDefaultRequestConfig(requestConfig)
                .build();
    }
 
    protected void copyResponseHeaders(HttpResponse proxyResponse, HttpServletRequest request, HttpServletResponse response, String url) {
        for (Header header : proxyResponse.getAllHeaders()) {
            copyResponseHeader(request, response, header, url);
        }
    }
 
    protected void copyResponseHeader(HttpServletRequest request, HttpServletResponse response, Header header, String url) {
        String headerName = header.getName();
        if (HOP_HEADERS.containsHeader(headerName)) {
            return;
        }
 
        String headerValue = header.getValue();
        if (headerName.equalsIgnoreCase(org.apache.http.cookie.SM.SET_COOKIE) || headerName.equalsIgnoreCase(org.apache.http.cookie.SM.SET_COOKIE2)) {
            copyProxyCookie(request, response, headerValue);
        } else if (headerName.equalsIgnoreCase(HttpHeaders.LOCATION)) {
            response.addHeader(headerName, rewriteUrlFromResponse(request, url, headerValue));
        } else {
            response.addHeader(headerName, headerValue);
        }
    }
 
    protected void copyProxyCookie(HttpServletRequest request, HttpServletResponse response, String headerValue) {
        String path = request.getContextPath() + request.getServletPath();
        if (path.isEmpty()) {
            path = "/";
        }
 
        for (HttpCookie cookie : HttpCookie.parse(headerValue)) {
            Cookie servletCookie = new Cookie(cookie.getName(), cookie.getValue());
            servletCookie.setComment(cookie.getComment());
            servletCookie.setMaxAge((int) cookie.getMaxAge());
            servletCookie.setPath(path);
 
            servletCookie.setSecure(cookie.getSecure());
            servletCookie.setVersion(cookie.getVersion());
            response.addCookie(servletCookie);
        }
    }
 
    protected String rewriteUrlFromResponse(HttpServletRequest request, String targetUri, String theUrl) {
        if (theUrl.startsWith(targetUri)) {
            StringBuffer curUrl = request.getRequestURL();
 
            int pos;
            if ((pos = curUrl.indexOf(HTTP_SLASH2)) >= 0) {
                if ((pos = curUrl.indexOf(HTTP_SLASH, pos + THREE)) >= 0) {
                    curUrl.setLength(pos);
                }
            }
 
            curUrl.append(request.getContextPath());
            curUrl.append(request.getServletPath());
            curUrl.append(theUrl, targetUri.length(), theUrl.length());
 
            return curUrl.toString();
        }
 
        return theUrl;
    }
 
    protected void copyResponseEntity(HttpResponse proxyResponse, HttpServletRequest request, HttpServletResponse response, ResEntity res) throws IOException {
        HttpEntity entity = proxyResponse.getEntity();
        if (null == entity) {
            return;
        }
 
        switch (res.getCategory()) {
            case 2:
                copeGeoService(proxyResponse, request, response, res);
                break;
            case 3:
                copeSjService(proxyResponse, request, response, res);
                break;
            default:
                entity.writeTo(response.getOutputStream());
                break;
        }
    }
 
    private void copeGeoService(HttpResponse proxyResponse, HttpServletRequest request, HttpServletResponse response, ResEntity res) throws IOException {
        if (StaticData.GET_CAPABILITIES.equals(request.getParameter(StaticData.REQUEST))) {
            //
        }
 
        proxyResponse.getEntity().writeTo(response.getOutputStream());
    }
 
    private void copeSjService(HttpResponse proxyResponse, HttpServletRequest request, HttpServletResponse response, ResEntity res) throws IOException {
        Header[] headers = proxyResponse.getHeaders("content-type");
        if (null != headers && headers.length > 0 && headers[0].getValue().contains(StaticData.TEXT_XML)) {
            String str = filterStr(request, response, res, EntityUtils.toString(proxyResponse.getEntity(), "UTF-8"));
            byte[] bytes = str.getBytes(StandardCharsets.UTF_8);
            response.setContentLength(bytes.length);
            response.getOutputStream().write(bytes);
        } else {
            proxyResponse.getEntity().writeTo(response.getOutputStream());
        }
    }
 
    private String filterStr(HttpServletRequest request, HttpServletResponse response, ResEntity res, String str) {
        if (str.contains(res.getUrl())) {
            String proxyUrl = res.getProxy().replace("{token}", response.getHeader("token"));
            proxyUrl = request.getRequestURL().substring(0, request.getRequestURL().indexOf(proxyUrl) + proxyUrl.length());
            str = str.replace(res.getUrl(), proxyUrl);
 
            if (!StringHelper.isEmpty(res.getArgs())) {
                // str = str.replace("?" + res.getArgs(), "").replace("&amp;" + res.getArgs(), "")
                str = str.replace("?" + res.getArgs() + "\"", "\"").replace("&amp;" + res.getArgs() + "\"", "\"")
                        .replace("?" + res.getArgs() + "&amp;", "?").replace("&amp;" + res.getArgs() + "&amp;", "&amp;");
            }
 
            if (StaticData.I3 == res.getCategory() && str.contains(StaticData.REST_LAYER)) {
                str = str.replace(res.getUrl().replace("/v6/wmts/", StaticData.REST_LAYER), proxyUrl.replace("/proxy/", "/proxy/rest/"));
            }
        }
 
        return str;
    }
}