pengjing 10 meses atrás
pai
commit
8e7242db92

+ 5 - 0
src/main/java/com/hz/employmentsite/AppConfig.java

@@ -78,6 +78,11 @@ public class AppConfig {
     @Value("${appconfig.wxconfig.accessScope}")
     public String wxAccessScope;
 
+    @Value("${appconfig.ztndatagdgovConfig.paasId}")
+    public String gdgov_paasId;
+    @Value("${appconfig.ztndatagdgovConfig.passToken}")
+    public String gdgov_passToken;
+
 
 
     /**

+ 1 - 0
src/main/java/com/hz/employmentsite/config/WebConfiguration.java

@@ -69,6 +69,7 @@ public class WebConfiguration implements WebMvcConfigurer {
         excludePath.add("/api/jobusermgr/recommendmgt/getListById");
         excludePath.add("/api/companyService/post/getPostByID");
         excludePath.add("/api/wx/**");
+        excludePath.add("/gdgovMapApi");
         excludePath.add("/static/**");  //静态资源
         excludePath.add("/mobile/**");  //静态资源
         excludePath.add("/web/**");  //静态资源

+ 299 - 0
src/main/java/com/hz/employmentsite/webservices/ztndata_gdgov/ProxyHandler.java

@@ -0,0 +1,299 @@
+package com.hz.employmentsite.webservices.ztndata_gdgov;
+
+import com.hz.employmentsite.AppConfig;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.beans.factory.annotation.Configurable;
+import org.springframework.stereotype.Component;
+
+import javax.servlet.ServletConfig;
+import javax.servlet.ServletException;
+import javax.servlet.http.HttpServlet;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import java.io.*;
+import java.net.HttpURLConnection;
+import java.net.URL;
+import java.net.URLDecoder;
+import java.net.URLEncoder;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.Map;
+
+@Component
+public class ProxyHandler extends HttpServlet implements Serializable {
+    private static final long serialVersionUID = 3561079438115778584L;
+    private final static Logger logger = LoggerFactory.getLogger(ProxyHandler.class);
+    private static final String CHARSET_UTF8 = "UTF-8"; // 默认字符集常量 : UTF-8
+    public static final String CONTENT_URL_NAME = "url";
+
+    @Autowired
+    private AppConfig appConfig;
+
+    public ProxyHandler() {
+    }
+
+    /**
+     * SERVELT 初始化
+     */
+    @Override
+    public void init(ServletConfig config) throws ServletException {
+        super.init();
+    }
+
+    /**
+     * doGet 请求
+     */
+    public void doGet(HttpServletRequest req, HttpServletResponse resp)
+            throws ServletException, IOException {
+        noSecurityRequest(req, resp);
+    }
+
+    private void noSecurityRequest(HttpServletRequest req,
+                                   HttpServletResponse resp) throws IOException {
+        logger.info("ProxyHandler noSecurityRequest 请求类型: GET");
+        String url0 = "";
+        OutputStream out = null;
+        HttpURLConnection conn = null;
+        // 获取请求的类型与字符集
+        String requestContent = req.getContentType();
+
+        String requestCharset = req.getCharacterEncoding();
+        StringBuffer requestContentType = new StringBuffer();
+        if (null != requestContent) {
+            requestContentType.append(requestContent);
+            if (null != requestCharset) {
+                requestContentType.append(";charset=").append(requestCharset);
+            }
+        }
+        try {
+            // 获取请求参数的字符串
+            String params = req.getQueryString();
+            params = params.replace("+", "%2B");
+            Map<String, String> paramValues = GetParamters(params);
+            url0 = URLDecoder.decode(paramValues.get("url"),"UTF-8");
+
+            // 请求转发
+            URL url = new URL(url0);
+
+            conn = (HttpURLConnection) url.openConnection();
+            conn.setRequestMethod("GET");
+            if (!requestContentType
+                    .toString().equals("")) {
+                conn.setRequestProperty("Content-Type", requestContentType
+                        .toString());
+            }
+            //添加请求头,paasId 与 paasToken 可从前端传递或者读取后端配置文件
+            String paasId = appConfig.gdgov_paasId, paasToken = appConfig.gdgov_passToken;
+            if (paramValues.containsKey("paasId")) {
+                paasId = paramValues.get("paasId");
+                paasToken = paramValues.get("paasToken");
+            }
+            HashMap<String, String> map = Signature.computeSignatureHeaders(paasId, paasToken);
+            if (paramValues.containsKey("serviceCode")) {
+
+                map.put("x-tif-signature", map.get("x-tif-signature").toUpperCase());
+                map.put("x-tif-serviceId", paramValues.get("serviceCode"));
+            }
+            for (String key : map.keySet()) {
+                conn.setRequestProperty(key, map.get(key));
+            }
+            logger.info("计算网关签名为:\n" + map);
+            conn.setDoOutput(true);
+            conn.setDoInput(true);
+            conn.setUseCaches(false);
+            // 获取请求的类型与字符集设置
+            String contentType = conn.getContentType();
+            String encoding = conn.getContentEncoding();
+            out = resp.getOutputStream();
+            // 设置返回的类型与字符集
+            resp.setContentType(contentType);
+            resp.setHeader("Content-Encoding", encoding);//正文解压缩方式
+            InputStream in = null;
+            if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
+                in = conn.getInputStream();
+            } else {
+                in = conn.getErrorStream();
+            }
+            out = resp.getOutputStream();
+            int len = 0;
+            byte[] b = new byte[1024];
+            while ((len = in.read(b)) > 0) {
+                out.write(b, 0, len);
+            }
+            out.flush();
+            logger.info("\n 请求地址: " + url0 + "\n 请求成功!");
+        } catch (Exception e) {
+            logger.error("请求地址: " + url0 + "\n 请求失败: " + e);
+        } finally {
+            try {
+                if (out != null) {
+                    out.close();
+                }
+                if (conn != null) {
+                    conn.disconnect();
+                }
+            } catch (Exception e) {
+                logger.error(e.toString());
+            }
+
+        }
+    }
+
+    private Map<String, String> GetParamters(String queryString) {
+        Map<String, String> pramValues = new HashMap<String, String>();
+        String[] paramNames = queryString.split("&");
+
+        for (int i = 0; i < paramNames.length; i++) {
+            String[] paramName = paramNames[i].split("=");
+
+            pramValues.put(paramName[0], paramName.length > 0 ? paramName[1] : "");
+        }
+
+        return pramValues;
+    }
+
+    public Map<String, Object> toMap(String url) {
+        Map<String, Object> map = null;
+        if ((url != null) && (url.indexOf("&") > -1) && (url.indexOf("=") > -1)) {
+            map = new HashMap<String, Object>();
+            String[] arrTemp = url.split("&");
+
+            for (String str : arrTemp) {
+                String[] qs = str.split("=", 2);
+                if (qs[0].indexOf("http://") == -1) {
+                    if (qs.length == 2)
+                        map.put(qs[0], qs[1]);
+                } else {
+                    String[] temp = qs[0].split("\\?");
+                    map.put(temp[(temp.length - 1)], qs[1]);
+                }
+            }
+        }
+        return map;
+    }
+
+    /**
+     * doPost 请求
+     */
+    public void doPost(HttpServletRequest request, HttpServletResponse response)
+            throws ServletException, IOException {
+        logger.info("请求类型: POST");
+        InputStream indoc = request.getInputStream();
+        // 获取请求参数
+        String url0 = request.getQueryString();
+
+        // 对请求参数进行解码操作
+        if (null != url0)
+            url0 = URLDecoder.decode(url0, CHARSET_UTF8);
+        // 获取请求类型与字符集
+        String requestContent = request.getContentType();
+        String requestCharset = request.getCharacterEncoding();
+        StringBuffer requestContentType = new StringBuffer();
+        if (null != requestContent) {
+            requestContentType.append(requestContent);
+            if (null != requestCharset) {
+                requestContentType.append(";charset=").append(requestCharset);
+            }
+        }
+        OutputStream out = response.getOutputStream();
+        try {
+            Map<String, String> paramValues = GetParamters(url0);
+            int urlIndex = url0.indexOf("url=");
+            if (urlIndex > 0) {
+                url0 = url0.substring(urlIndex);
+            }
+            if (url0.startsWith("url=")) {
+                String urlString = url0.substring(4);
+                URL url = new URL(urlString);
+                BufferedInputStream in = null;
+                HttpURLConnection connection = null;
+                byte[] bs = null;
+                if (url != null) {
+                    try {
+                        // 转发请求
+                        connection = (HttpURLConnection) url.openConnection();
+                        connection.setRequestMethod("POST");
+                        connection.setRequestProperty("Content-Type",
+                                requestContentType.toString());
+                        connection.setDoInput(true);
+                        connection.setDoOutput(true);
+                        //添加请求头,paasId 与 paasToken 可从前端传递或者读取后端配置文件
+                        String paasId = "", paasToken = "";
+                        if (paramValues.containsKey("paasId")) {
+                            paasId = paramValues.get("paasId");
+                            paasToken = paramValues.get("paasToken");
+                        } else {
+                            /*paasId = gatewayConfig.getPaasId();
+                            paasToken = gatewayConfig.getPaasToken();*/
+                            paasId = appConfig.gdgov_paasId;
+                            paasToken = appConfig.gdgov_passToken;
+                        }
+
+                        HashMap<String, String> map = Signature.computeSignatureHeaders(paasId, paasToken);
+                        if (paramValues.containsKey("serviceCode")) {
+                            map.put("x-tif-signature", map.get("x-tif-signature").toUpperCase());
+                            map.put("x-tif-serviceId", paramValues.get("serviceCode"));
+                        }
+                        for (String key : map.keySet()) {
+                            connection.setRequestProperty(key, map.get(key));
+                        }
+                        OutputStream toserver = connection.getOutputStream();
+                        int l = 0;
+                        while ((l = indoc.read()) != -1) {
+                            toserver.write(l);
+                        }
+                        toserver.flush();
+                        toserver.close();
+                        // 获取转发返回的类型与字符集
+                        String responseContentType = connection
+                                .getContentType();
+                        String responseCharset = connection
+                                .getContentEncoding();
+                        // 将转发返回的类型与字符集设置到返回的参数中
+                        response.setContentType(responseContentType);
+
+                        response.setCharacterEncoding(responseCharset);
+                        // 读取响应信息,并将响应发送到客户端
+                        in = new BufferedInputStream(connection
+                                .getInputStream());
+                        bs = new byte[1024];
+                        int startpos = 0;
+                        int num = 0;
+                        num = in.read(bs, startpos, 1024);
+                        logger.info("返回信息:");
+                        while (num != -1) {
+                            out.write(bs, 0, num);
+                            logger.info(new String(bs));
+                            num = in.read(bs, 0, 1024);
+                        }
+                        logger.info("\n 请求地址: " + url0 + "\n 请求成功!");
+                    } catch (IOException e) {
+                        logger.error("请求地址: " + url0 + "\n 请求失败!" + e);
+                    } finally {
+                        if (in != null) {
+                            try {
+                                in.close();
+                            } catch (Exception ex) {
+                            }
+                        }
+                        if (connection != null) {
+                            try {
+                                connection.disconnect();
+                            } catch (Exception ex) {
+                            }
+                        }
+                    }
+                }
+            }
+        } catch (Exception e) {
+            logger.error(e.toString());
+        } finally {
+            if (out != null) {
+                out.flush();
+                out.close();
+            }
+        }
+    }
+}

+ 25 - 0
src/main/java/com/hz/employmentsite/webservices/ztndata_gdgov/ServletConfig.java

@@ -0,0 +1,25 @@
+package com.hz.employmentsite.webservices.ztndata_gdgov;
+
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.web.servlet.ServletRegistrationBean;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+
+@Configuration
+public class ServletConfig {
+
+    @Autowired
+    private ProxyHandler proxyHandler;
+
+
+    @Bean
+    public ServletRegistrationBean getServletRegistrationBean() {
+        //写请求前缀
+        String format = String.format("/%s/*", "gdgovMapApi");
+        ServletRegistrationBean bean = new ServletRegistrationBean(proxyHandler);
+        bean.addUrlMappings(format);
+        return bean;
+    }
+
+
+}

+ 62 - 0
src/main/java/com/hz/employmentsite/webservices/ztndata_gdgov/Signature.java

@@ -0,0 +1,62 @@
+package com.hz.employmentsite.webservices.ztndata_gdgov;
+
+import org.springframework.stereotype.Component;
+
+import java.security.MessageDigest;
+import java.util.Date;
+import java.util.HashMap;
+
+public class Signature {
+    /**
+     * 计算签名,返回请求求需要使用的参数
+     */
+    public static HashMap<String, String> computeSignatureHeaders(String paasId, String paasToken) throws
+            Exception {
+        if (paasId == null || paasId.isEmpty() || paasToken == null || paasToken.isEmpty()) {
+            throw new Exception("paasId,paasToken must be set");
+        }
+        HashMap<String, String> map = new HashMap<String, String>();
+        long now = new Date().getTime();
+        String timestamp = Long.toString((long) Math.floor(now / 1000));
+        String nonce = Long.toHexString(now) + "-" + Long.toHexString((long) Math.floor(Math.random() *
+                0xFFFFFF));
+        map.put("x-tif-paasId", paasId);
+        map.put("x-tif-timestamp", timestamp);
+        map.put("x-tif-nonce", nonce);
+        map.put("x-tif-signature", toSHA256(timestamp + paasToken + nonce + timestamp));
+        return map;
+    }
+
+    /**
+     * 签名计算
+     */
+    protected static String toSHA256(String str) throws Exception {
+        MessageDigest messageDigest;
+        String encodeStr = "";
+        try {
+            messageDigest = MessageDigest.getInstance("SHA-256");
+            messageDigest.update(str.getBytes("UTF-8"));
+            encodeStr = byte2Hex(messageDigest.digest());
+        } catch (Exception e) {
+            throw e;
+        }
+        return encodeStr;
+    }
+
+    /**
+     * byte 转换成 16 进制
+     */
+    protected static String byte2Hex(byte[] bytes) {
+        StringBuffer stringBuffer = new StringBuffer();
+        String temp = null;
+        for (int i = 0; i < bytes.length; i++) {
+            temp = Integer.toHexString(bytes[i] & 0xFF);
+            if (temp.length() == 1) {
+                stringBuffer.append("0");
+            }
+            stringBuffer.append(temp);
+        }
+        return stringBuffer.toString();
+    }
+
+}

+ 3 - 0
src/main/resources/application.yml

@@ -123,5 +123,8 @@ appconfig:
     appSecret: '0d37c99bf2edd9ef3d839869bfa724ad'
     wxMessageBaseUrl: 'http://www.bowintek.com/hzyz/mobile/index.html/#'
     accessScope: 'snsapi_base'
+  ztndatagdgovConfig:
+    paasId: 'C90-44000930'
+    passToken: '7499876b824144c3b1675f8c1412c24c'