北京经济技术开发区经开区虚拟城市项目-【后端】-服务,Poi,企业,地块等定制接口
13693261870
2023-10-05 8fa8df4fbb39e4ca98d5dee69cf4f334f4bde057
添加web工具类
已添加5个文件
已修改2个文件
1126 ■■■■■ 文件已修改
pom.xml 6 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/main/java/com/smartearth/poiexcel/config/RestTemplateConfig.java 100 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/main/java/com/smartearth/poiexcel/entity/StaticData.java 330 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/main/java/com/smartearth/poiexcel/service/EntService.java 64 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/main/java/com/smartearth/poiexcel/utils/HttpHelper.java 273 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/main/java/com/smartearth/poiexcel/utils/RestHelper.java 267 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/main/java/com/smartearth/poiexcel/utils/SpringContextHelper.java 86 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
pom.xml
@@ -116,6 +116,7 @@
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <!--mybatis-plus-->
        <dependency>
            <groupId>com.baomidou</groupId>
@@ -143,6 +144,11 @@
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <!--httpclient-->
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
        </dependency>
    </dependencies>
    <build>
src/main/java/com/smartearth/poiexcel/config/RestTemplateConfig.java
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,100 @@
package com.smartearth.poiexcel.config;
import org.apache.http.client.HttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.client.RestTemplate;
import java.nio.charset.StandardCharsets;
import java.util.List;
/**
 * Rest模板配置类
 * @author WWW
 */
@Configuration
@ConditionalOnClass(value = {RestTemplate.class, HttpClient.class})
public class RestTemplateConfig {
    /**
     * è¿žæŽ¥æ± çš„æœ€å¤§è¿žæŽ¥æ•°é»˜è®¤ä¸º0,不限制
     */
    @Value("${remote.maxTotalConnect:0}")
    private int maxTotalConnect;
    /**
     * å•个主机的最大连接数
     */
    @Value("${remote.maxConnectPerRoute:1000}")
    private int maxConnectPerRoute;
    /**
     * è¿žæŽ¥è¶…时默认5s,-1为不限制
     */
    @Value("${remote.connectTimeout:5000}")
    private int connectTimeout;
    /**
     * è¯»å–超时默认30s,-1为不限制
     */
    @Value("${remote.readTimeout:30000}")
    private int readTimeout;
    /**
     * åˆ›å»ºHTTP客户端工厂
     *
     * @return å®¢æˆ·ç«¯å·¥åŽ‚
     */
    private ClientHttpRequestFactory createFactory() {
        if (this.maxTotalConnect <= 0) {
            SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
            factory.setConnectTimeout(this.connectTimeout);
            factory.setReadTimeout(this.readTimeout);
            return factory;
        }
        HttpClient httpClient = HttpClientBuilder.create().setMaxConnTotal(this.maxTotalConnect).setMaxConnPerRoute(this.maxConnectPerRoute).build();
        HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(httpClient);
        factory.setConnectTimeout(this.connectTimeout);
        factory.setReadTimeout(this.readTimeout);
        return factory;
    }
    /**
     * åˆå§‹åŒ–RestTemplate,并加入spring的Bean工厂,由spring统一管理
     * å¿…须加注解@LoadBalanced
     *
     * @return
     */
    @Bean
    @ConditionalOnMissingBean(RestTemplate.class)
    public RestTemplate getRestTemplate() {
        RestTemplate restTemplate = new RestTemplate(this.createFactory());
        List<HttpMessageConverter<?>> converterList = restTemplate.getMessageConverters();
        // é‡æ–°è®¾ç½®StringHttpMessageConverter字符集为UTF-8,解决中文乱码问题
        HttpMessageConverter<?> converterTarget = null;
        for (HttpMessageConverter<?> item : converterList) {
            if (StringHttpMessageConverter.class == item.getClass()) {
                converterTarget = item;
                break;
            }
        }
        if (null != converterTarget) {
            converterList.remove(converterTarget);
        }
        converterList.add(1, new StringHttpMessageConverter(StandardCharsets.UTF_8));
        return restTemplate;
    }
}
src/main/java/com/smartearth/poiexcel/entity/StaticData.java
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,330 @@
package com.smartearth.poiexcel.entity;
import com.alibaba.fastjson.JSON;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
 * é™æ€æ•°æ®ç±»
 * @author WWW
 */
public class StaticData {
    /**
     * æƒé™æŽ’除路径:/proxy,要求全部小写
     */
    public static String[] EXCLUDE_PATH = new String[]{"/sign/", "/perms/", "/floatserver/", "/proxy/", "/swagger", "/error"};
    public final static int I0 = 0;
    public final static int I1 = 1;
    public final static int I2 = 2;
    public final static int I3 = 3;
    public final static int I4 = 4;
    public final static int I5 = 5;
    public final static int I6 = 6;
    public final static int I8 = 8;
    public final static int NINE = 9;
    public final static int TEN = 10;
    public final static int SIXTEEN = 16;
    public final static int ONE_HUNDRED = 100;
    public final static int TWO_HUNDRED = 200;
    public final static int ONE_HUNDRED_THOUSAND = 100000;
    public static final double D05 = 0.05;
    public static final double D90 = 90.0;
    public static final double D100 = 100.0;
    public static final double D1024 = 1024.0;
    public static final double D1050 = 1050.0;
    public static final int I12 = 12;
    public static final int I23 = 23;
    public static final int I24 = 24;
    public static final int I31 = 31;
    public static final int I50 = 50;
    public static final int I60 = 60;
    public static final int I64 = 64;
    public static final int I90 = 90;
    public static final int I90_NEG = -90;
    public final static int I100 = 100;
    public static final int I120 = 120;
    public static final int I180 = 180;
    public static final int I180_NEG = -180;
    public static final int I200 = 200;
    public static final int I500 = 500;
    public static final int I1000 = 1000;
    public static final int I1024 = 1024;
    public static final int I2050 = 2050;
    public static final int I4326 = 4326;
    public static final int I4490 = 4490;
    public static final int I104903 = 104903;
    public final static String S1 = "1";
    public final static String EQ = "=";
    public final static String POINT = ".";
    public final static String COMMA = ",";
    public final static String TILDE = "~";
    public final static String QUESTION = "?";
    public final static String BACKSLASH = "\\\\";
    public final static String SINGLE_QUOTES = "'";
    public final static String BBOREHOLE = "bborehole";
    public final static String AK = "?ak=";
    public final static String REST_LAYER = "/v6/rest/";
    public final static String TEXT_XML = "text/xml";
    public final static String SLASH = "/";
    public final static String IN = "in";
    public final static String ZIP = ".zip";
    public final static String XLS = ".xls";
    public final static String XLSX = ".xlsx";
    public final static String MDB = ".mdb";
    public final static String SHP = ".shp";
    public final static String NGDB = "gdb";
    public final static String GDB = ".gdb";
    public final static String JPG = ".jpg";
    public final static String JP2 = ".jp2";
    public final static String IMG = ".img";
    public final static String MPT = ".mpt";
    public final static String D3DML = ".3dml";
    public final static String TIF = ".tif";
    public final static String TIFF = ".tiff";
    public final static String LAS = ".las";
    public final static String OSGB = ".osgb";
    public final static String NULL = "null";
    public static String ADMIN = "admin";
    public final static String SYS_META = "sysmeta";
    public final static String VERSION = "1.0.0";
    public final static String TOKEN_KEY = "token";
    public final static String TOKEN_COOKIE_KEY = "token";
    public final static String TEXT_ENCODER = "UTF-8";
    public final static String CHECK_MAIN = "checkMain";
    public final static String OBJECT = "java.lang.Object";
    public final static String DRUID_COOKIE_KEY = "JSESSIONID";
    public final static String YES = "YES";
    public final static String NO = "NO";
    public final static String DOM = "DOM";
    public final static String LAYERS = "layers";
    public final static String REQUEST = "request";
    public final static String SERVICE = "service";
    public final static String GET_CAPABILITIES = "GetCapabilities";
    public final static String SUCCESS = "$SUCCESS";
    public final static String LINESTRING = "LINESTRING";
    public final static String MULTILINESTRING = "MULTILINESTRING";
    public final static String POLYGON = "POLYGON";
    public final static String MULTIPOLYGON = "MULTIPOLYGON";
    public final static String MULTICURVE = "MULTICURVE";
    public final static String COMPOUNDCURVE = "COMPOUNDCURVE";
    public final static String QUERYABLE = "<Layer queryable=\"1\" opaque=\"0\">";
    public static final String NO_FILE = JSON.toJSONString(new ResponseMsg<String>(HttpStatus.NOT_FOUND, "文件找不到"));
    /**
     * æœˆçƒ2000坐标系的WKT
     */
    public static final String MOON_2000_WKT = "GEOGCS[\"GCS_Moon_2000\",\r\n" +
            "    DATUM[\"D_Moon_2000\",\r\n" +
            "        SPHEROID[\"Moon_2000_IAU_IAG\",1737400,0,\r\n" +
            "            AUTHORITY[\"ESRI\",\"107903\"]],\r\n" +
            "        AUTHORITY[\"ESRI\",\"106903\"]],\r\n" +
            "    PRIMEM[\"Reference_Meridian\",0,\r\n" +
            "        AUTHORITY[\"ESRI\",\"108900\"]],\r\n" +
            "    UNIT[\"degree\",0.0174532925199433,\r\n" +
            "        AUTHORITY[\"EPSG\",\"9122\"]],\r\n" +
            "    AUTHORITY[\"ESRI\",\"104903\"]]";
    public final static String CGCS2000 = "CGCS2000";
    public final static String MOON200 = "GCS_Moon_2000";
    public final static List<String> EPSGS = new ArrayList<>(Arrays.asList("EPSG:4326", "EPSG:4490", "ESRI:104903"));
    /**
     * 16进制
     */
    public static final char[] HEX_DIGITS = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
    /**
     * å¯†ç æ­£åˆ™è¡¨è¾¾å¼
     */
    public final static String PWD_REG = "^(?![a-zA-Z]+$)(?![A-Z0-9]+$)(?![A-Z\\W!@#$%^&*`~()\\-_+=,.?;<>]+$)(?![a-z0-9]+$)(?![a-z\\W!@#$%^&*`~()\\-_+=,.?;<>]+$)(?![0-9\\W!@#$%^&*`~()\\-_+=,.?;<>]+$)[a-zA-Z0-9\\W!@#$%^&*`~()\\-_+=,.?;<>]{12,20}$";
    /**
     * æ …格数据扩展名
     */
    public final static List<String> RASTER_EXT = new ArrayList<>(Arrays.asList(".img", ".tif", ".tiff", ".jpg", ".jp2"));
    /**
     * MPT文件扩展名
     */
    public final static List<String> MPT_EXT = new ArrayList<>(Arrays.asList(".midx", ".strmi", ".ei.midx", ".ei.mpt", ".ei.strmi"));
    /**
     * JPG文件扩展名
     */
    public final static List<String> JPG_EXT = new ArrayList<>(Arrays.asList(".jpg.aux.xml", ".jpg.ovr", ".jpg.xml", ".jgw", ".prj"));
    /**
     * JP2文件扩展名
     */
    public final static List<String> JP2_EXT = new ArrayList<>(Arrays.asList(".jp2.aux.xml", ".jp2.ovr", ".jp2.xml", ".jgw", ".prj", ".jp2.html", ".jp2.txt"));
    /**
     * IMG文件扩展名
     */
    public final static List<String> IMG_EXT = new ArrayList<>(Arrays.asList(".rrd", ".img.aux.xml", ".hdr", ".img.enp", ".img.xml"));
    /**
     * TIF文件扩展名
     */
    public final static List<String> TIF_EXT = new ArrayList<>(Arrays.asList(".prj", ".tfw", ".aux", ".tif.ovr", ".tif.aux.xml", ".tif.xml"));
    /**
     * TIFF文件扩展名
     */
    public final static List<String> TIFF_EXT = new ArrayList<>(Arrays.asList(".prj", ".tfw", ".aux", ".tiff.ovr", ".tiff.aux.xml", ".tiff.xml"));
    /**
     * SHP文件扩展名
     */
    public final static List<String> SHP_EXT = new ArrayList<>(Arrays.asList(".shx", ".dbf", ".prj", ".cpg"));
    /**
     * Mapper排除扩展名
     */
    public final static List<String> MAPPER_EXCLUDE_EXT = new ArrayList<>(Arrays.asList(".jpg.aux.xml", ".jpg.xml", ".jp2.aux.xml", ".jp2.xml", ".jp2.html", ".jp2.txt", ".img.aux.xml", ".img.xml", ".tif.aux.xml", ".tif.xml", ".tiff.aux.xml", ".tiff.xml", ".shp.xml", ".ecw.xml", "ecw.aux.xml"));
    /**
     * æ‰€æœ‰æ–‡ä»¶æ‰©å±•名
     */
    public final static List<String> ALL_EXTENSION = new ArrayList<>(Arrays.asList(".txt", ".xml", ".pdf", ".xls", ".xlsx", ".doc", ".docx", ".ppt", ".pptx", ".shp", ".gdb", ".mdb", ".dwg", ".las", ".laz", ".cpt", ".mpt", ".ei.mpt", ".fly", ".efb", ".g3d", ".fbx", ".obj", ".3dm", ".3dml", ".osgb", ".rvt", ".ifc", ".jpg", ".jp2", ".png", ".img", ".tif", ".tiff", ".dem", ".bmp", ".gif", ".rmvb", ".rm", ".mp3", ".mp4", ".avi", ".wma", ".wmv", ".7z", ".rar", ".zip", ".csv"));
    /**
     * æ’入排除字段
     */
    public final static List<String> INSERT_EXCLUDE_FIELDS = new ArrayList<>(Arrays.asList("gid", "objectid", "updateuser", "updatetime", "shape_leng", "shape_area", "serialVersionUID", "dirName", "depName", "verName", "createName", "updateName"));
    /**
     * æ›´æ–°æŽ’除字段
     */
    public final static List<String> UPDATE_EXCLUDE_FIELDS = new ArrayList<>(Arrays.asList("objectid", "createuser", "createtime", "shape_leng", "shape_area", "serialVersionUID", "dirName", "depName", "verName", "createName", "updateName"));
    /**
     * è¯»å–排除字段
     */
    public final static List<String> READ_EXCLUDE_FIELDS = new ArrayList<>(Arrays.asList("gid", "eventid", "parentid", "objectid", "dirid", "depid", "verid", "createtime", "createuser", "updateuser", "updatetime", "shape_leng", "shape_area", "serialversionuid", "dirname", "depname", "vername", "createname", "updatename"));
    /**
     * MDB排除字段
     */
    public final static List<String> MDB_EXCLUDE_FIELDS = new ArrayList<>(Arrays.asList("Shape", "SHAPE_LENG", "Shape_Length", "Shape_Area", "OBJECTID_1"));
    /**
     * æ ‡ç»˜Shp排除字段
     */
    public final static List<String> MARK_EXCLUDE_FIELDS = new ArrayList<>(Arrays.asList("wkt", "geom", "objectid", "shape_leng", "shape_area", "serialVersionUID", "dirName", "depName", "verName", "createName", "updateName"));
    /**
     * GDB排除字段
     */
    public final static List<String> GDB_EXCLUDE_FIELDS = new ArrayList<>(Arrays.asList("geom", "objectid", "shape_leng", "shape_area", "serialVersionUID", "dirName", "depName", "verName", "createName", "updateName"));
    /**
     * ç®¡çº¿åˆ†æžè¡¨åé›†åˆ
     */
    public final static List<String> PIPE_ANALYSIS_TABS = new ArrayList<>(Arrays.asList("bd.dlg_25w_hydl", "bd.dlg_25w_lrdl", "bd.dlg_25w_lrrl", "bd.dlg_25w_hyda"));
    /**
     * ç®¡çº¿æŽ’除字段
     */
    public final static List<String> PIPE_EXCLUDE_FIELDS = new ArrayList<>(Arrays.asList("serialVersionUID", "tabs", "pwd", "gid", "wkt"));
}
src/main/java/com/smartearth/poiexcel/service/EntService.java
@@ -1,9 +1,18 @@
package com.smartearth.poiexcel.service;
import com.smartearth.poiexcel.mapper.EntMapper;
import com.smartearth.poiexcel.utils.RestHelper;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import javax.annotation.Resource;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
/**
 * ä¼ä¸šæœåŠ¡ç±»
@@ -15,5 +24,58 @@
    @Resource
    EntMapper entMapper;
    //
    @Value("${qylweb.url}")
    String qylwebUrl;
    private final static Log log = LogFactory.getLog(EntService.class);
    /**
     * post请求(Rest)
     */
    public <T> T postForRest(String url, Map<String, Object> map, Class<T> clazz) {
        RestTemplate rest = RestHelper.getRestTemplate();
        return rest.postForObject(url, map, clazz);
    }
    /**
     * delete请求(Rest)
     */
    public Object deleteForRest(String url, Map<String, Object> map) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<?> entity = new HttpEntity<>(map, headers);
        RestTemplate rest = RestHelper.getRestTemplate();
        ResponseEntity<Object> rs = rest.exchange(url, HttpMethod.DELETE, entity, Object.class);
        return rs.getBody();
    }
    /**
     * èŽ·å–Map数据
     */
    public <T> Map<String, Object> getMapData(T t) {
        Map<String, Object> map = new HashMap<>(1);
        Field[] fields = t.getClass().getDeclaredFields();
        for (Field field : fields) {
            try {
                if ("serialVersionUID".equals(field.getName())) {
                    continue;
                }
                field.setAccessible(true);
                Object obj = field.get(t);
                map.put(field.getName(), obj);
            } catch (Exception ex) {
                //
            }
        }
        return map;
    }
}
src/main/java/com/smartearth/poiexcel/utils/HttpHelper.java
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,273 @@
package com.smartearth.poiexcel.utils;
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.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, 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);
            }
        } 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) throws IOException {
        HttpEntity entity = proxyResponse.getEntity();
        if (null == entity) {
            return;
        }
        entity.writeTo(response.getOutputStream());
    }
}
src/main/java/com/smartearth/poiexcel/utils/RestHelper.java
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,267 @@
package com.smartearth.poiexcel.utils;
import com.smartearth.poiexcel.entity.StaticData;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.web.client.RestTemplate;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
 * Rest服务帮助类
 * @author WWW
 */
public class RestHelper {
    private static RestTemplate restTemplate;
    private final static Log log = LogFactory.getLog(RestHelper.class);
    /**
     * èŽ·å–RestTemplate
     *
     * @return RestTemplate
     */
    public static RestTemplate getRestTemplate() {
        if (restTemplate == null) {
            restTemplate = SpringContextHelper.getBean(RestTemplate.class);
        }
        return restTemplate;
    }
    /**
     * Get请求-HttpURLConnection
     *
     * @param url URL地址
     * @return å­—符串
     * @throws IOException IO异常
     */
    public static String getForConn(String url) throws IOException {
        BufferedReader br = null;
        HttpURLConnection conn = null;
        try {
            URL restUrl = new URL(url);
            conn = (HttpURLConnection) restUrl.openConnection();
            // POST,GET,PUT,DELETE
            conn.setRequestMethod("GET");
            conn.setRequestProperty("Accept", "application/json");
            br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            StringBuilder sb = new StringBuilder();
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
            return sb.toString();
        } finally {
            if (br != null) {
                br.close();
            }
            if (conn != null) {
                conn.disconnect();
            }
        }
    }
    /**
     * Post请求-HttpURLConnection
     *
     * @param url   URL地址
     * @param query æŸ¥è¯¢æ¡ä»¶
     * @return å­—符串
     * @throws IOException IO异常
     */
    public static String postForConn(String url, String query) throws IOException {
        BufferedReader br = null;
        HttpURLConnection conn = null;
        try {
            URL restUrl = new URL(url);
            conn = (HttpURLConnection) restUrl.openConnection();
            // POST,GET,PUT,DELETE
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "application/json");
            conn.setDoOutput(true);
            PrintStream ps = new PrintStream(conn.getOutputStream());
            ps.print(query);
            ps.close();
            // OutputStream out = conn.getOutputStream()
            // out.write(query.getBytes())
            // out.close()
            br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            StringBuilder sb = new StringBuilder();
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
            return sb.toString();
        } finally {
            if (br != null) {
                br.close();
            }
            if (conn != null) {
                conn.disconnect();
            }
        }
    }
    /**
     * Get请求-CloseableHttpClient
     *
     * @param uri Uri地址
     * @return å“åº”字符串
     */
    public static String get(String uri) {
        try {
            CloseableHttpClient httpClient = HttpClients.custom().build();
            HttpGet httpGet = new HttpGet(uri);
            CloseableHttpResponse closeResponse = httpClient.execute(httpGet);
            // å–出返回体
            HttpEntity entity = closeResponse.getEntity();
            return EntityUtils.toString(entity, StaticData.TEXT_ENCODER);
        } catch (Exception ex) {
            log.error(ex.getMessage(), ex);
            return getErrorInfo(uri, ex);
        }
    }
    /**
     * Post请求-CloseableHttpClient
     *
     * @param uri      Uri地址
     * @param postData å¾…发送数据
     * @return å“åº”字符串
     */
    public static String post(String uri, List<NameValuePair> postData) {
        try {
            CloseableHttpClient httpClient = HttpClients.custom().build();
            UrlEncodedFormEntity postEntity = new UrlEncodedFormEntity(postData, StaticData.TEXT_ENCODER);
            HttpPost httpPost = new HttpPost(uri);
            httpPost.setEntity(postEntity);
            CloseableHttpResponse closeResponse = httpClient.execute(httpPost);
            // å–出返回体
            HttpEntity entity = closeResponse.getEntity();
            return EntityUtils.toString(entity, StaticData.TEXT_ENCODER);
        } catch (Exception ex) {
            log.error(ex.getMessage(), ex);
            return getErrorInfo(uri, ex);
        }
    }
    /**
     * èŽ·å–é”™è¯¯ä¿¡æ¯
     *
     * @param uri Uri地址
     * @param ex  å¼‚常
     * @return é”™è¯¯ä¿¡æ¯
     */
    public static String getErrorInfo(String uri, Exception ex) {
        Map<String, Object> map = new LinkedHashMap<>();
        map.put("result", null);
        map.put("message", ex.getMessage());
        map.put("code", 400);
        map.put("uri", uri);
        //map.put("tag", StaticData.CACHE_PREFIX)
        return map.toString();
    }
    /**
     * GET请求(REST)
     */
    public static String getForRest(String uri) {
        RestTemplate rest = getRestTemplate();
        return rest.getForObject(uri, String.class);
    }
    /**
     * GET请求(REST)
     */
    public static <T> T getForRest(String uri, Class<T> clazz) {
        RestTemplate rest = getRestTemplate();
        return rest.getForObject(uri, clazz);
    }
    /**
     * POST请求(REST)
     */
    public static String postForRest(String uri, Map<String, Object> map) {
        RestTemplate rest = getRestTemplate();
        return rest.postForObject(uri, map, String.class);
    }
    /**
     * POST请求(REST)
     */
    public static <T> String postForRest(String uri, List<T> list) {
        RestTemplate rest = getRestTemplate();
        return rest.postForObject(uri, list, String.class);
    }
    /**
     * POST请求(REST)
     */
    public static <T> String postForRest(String uri, T t) {
        RestTemplate rest = getRestTemplate();
        return rest.postForObject(uri, t, String.class);
    }
    /**
     * DELETE请求(REST)
     */
    public static void deleteForRest(String uri) {
        RestTemplate rest = getRestTemplate();
        rest.delete(uri);
    }
    /**
     * DELETE请求(REST)
     */
    public static void deleteForRest(String uri, Map<String, Object> map) {
        RestTemplate rest = getRestTemplate();
        rest.delete(uri, map);
    }
}
src/main/java/com/smartearth/poiexcel/utils/SpringContextHelper.java
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,86 @@
package com.smartearth.poiexcel.utils;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
/**
 * Spring上下文帮助类
 * @author WWW
 */
@Component
public class SpringContextHelper implements ApplicationContextAware {
    private static ApplicationContext context = null;
    /**
     * è®¾ç½®åº”用程序上下文
     *
     * @param applicationContext
     * @throws BeansException
     */
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        context = applicationContext;
    }
    /**
     * æ ¹æ®åç§°èŽ·å–Bean
     *
     * @param name ç±»åç§°
     * @return
     */
    public static <T> T getBean(String name) {
        return (T) context.getBean(name);
    }
    /**
     * æ ¹æ®ç±»åž‹èŽ·å–Bean
     *
     * @param clazz ç±»
     * @param <T>   æ³›åž‹
     * @return
     */
    public static <T> T getBean(Class<T> clazz) {
        return context.getBean(clazz);
    }
    /**
     * åˆ¤æ–­æ˜¯å¦åŒ…含对应名称的Bean对象
     *
     * @param name Bean名称
     * @return åŒ…含:返回true,否则返回false。
     */
    public static boolean containsBean(String name) {
        return context.containsBean(name);
    }
    /**
     * èŽ·å–å¯¹åº”Bean名称的类型
     *
     * @param name Bean名称
     * @return è¿”回对应的Bean类型
     */
    public static Class<?> getType(String name) {
        return context.getType(name);
    }
    /**
     * èŽ·å–ä¸Šä¸‹æ–‡å¯¹è±¡ï¼Œå¯è¿›è¡Œå„ç§Spring的上下文操作
     *
     * @return Spring上下文对象
     */
    public static ApplicationContext getContext() {
        return context;
    }
    /**
     * èŽ·å–å½“å‰çŽ¯å¢ƒ
     *
     * @return Profile
     */
    public static String getActiveProfile() {
        return context.getEnvironment().getActiveProfiles()[0];
    }
}