You can not select more than 25 topics
			Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
		
		
		
		
			
				
					
					
						
							367 lines
						
					
					
						
							13 KiB
						
					
					
				
			
		
		
	
	
							367 lines
						
					
					
						
							13 KiB
						
					
					
				package com.ynxbd.common.helper.common;
 | 
						|
 | 
						|
import org.apache.commons.lang3.StringUtils;
 | 
						|
 | 
						|
import javax.servlet.ServletOutputStream;
 | 
						|
import javax.servlet.http.HttpServletRequest;
 | 
						|
import javax.servlet.http.HttpServletResponse;
 | 
						|
import java.io.*;
 | 
						|
import java.net.*;
 | 
						|
import java.nio.charset.StandardCharsets;
 | 
						|
import java.util.Enumeration;
 | 
						|
import java.util.regex.Matcher;
 | 
						|
import java.util.regex.Pattern;
 | 
						|
 | 
						|
/**
 | 
						|
 * @Author wsq
 | 
						|
 * @Date 2021/2/8 14:53
 | 
						|
 * @Copyright @ 2020 云南新八达科技有限公司 All rights reserved.
 | 
						|
 */
 | 
						|
public class HttpHelper {
 | 
						|
 | 
						|
    /**
 | 
						|
     * 获取访问者真实IP地址
 | 
						|
     */
 | 
						|
    public static String getVisitorIP(HttpServletRequest request) {
 | 
						|
        String ip = request.getHeader("X-Real-IP");
 | 
						|
        if (!StringUtils.isBlank(ip) && !"unknown".equalsIgnoreCase(ip)) {
 | 
						|
            if (ip.contains("../") || ip.contains("..\\")) {
 | 
						|
                return "";
 | 
						|
            }
 | 
						|
            return ip;
 | 
						|
        }
 | 
						|
        ip = request.getHeader("X-Forwarded-For");
 | 
						|
        if (!StringUtils.isBlank(ip) && !"unknown".equalsIgnoreCase(ip)) {
 | 
						|
            // 多次反向代理后会有多个IP值,第一个为真实IP。
 | 
						|
            int index = ip.indexOf(',');
 | 
						|
            if (index != -1) {
 | 
						|
                ip = ip.substring(0, index);
 | 
						|
            }
 | 
						|
            if (ip.contains("../") || ip.contains("..\\")) {
 | 
						|
                return "";
 | 
						|
            }
 | 
						|
            return ip;
 | 
						|
        } else {
 | 
						|
            ip = request.getRemoteAddr();
 | 
						|
            if (ip.contains("../") || ip.contains("..\\")) {
 | 
						|
                return "";
 | 
						|
            }
 | 
						|
            if (ip.equals("0:0:0:0:0:0:0:1")) {
 | 
						|
                ip = "127.0.0.1";
 | 
						|
            }
 | 
						|
            return ip;
 | 
						|
        }
 | 
						|
    }
 | 
						|
 | 
						|
 | 
						|
    public static String getIpAddress(HttpServletRequest request) {
 | 
						|
        String remoteAddress = request.getRemoteAddr();
 | 
						|
        String forwarded = request.getHeader("X-Forwarded-For");
 | 
						|
        String realIp = request.getHeader("X-Real-IP");
 | 
						|
 | 
						|
        String ip;
 | 
						|
        if (realIp == null) {
 | 
						|
            if (forwarded == null) {
 | 
						|
                ip = remoteAddress;
 | 
						|
            } else {
 | 
						|
                ip = remoteAddress + "/" + forwarded.split(",")[0];
 | 
						|
            }
 | 
						|
        } else {
 | 
						|
            if (realIp.equals(forwarded)) {
 | 
						|
                ip = realIp;
 | 
						|
            } else {
 | 
						|
                if (forwarded != null) {
 | 
						|
                    forwarded = forwarded.split(",")[0];
 | 
						|
                }
 | 
						|
                ip = forwarded == null ? realIp : realIp + "/" + forwarded;
 | 
						|
            }
 | 
						|
        }
 | 
						|
        return ip;
 | 
						|
    }
 | 
						|
 | 
						|
    /**
 | 
						|
     * 获取本机的内网ip地址
 | 
						|
     */
 | 
						|
    public static String getInIP() {
 | 
						|
        String resultIp = null;
 | 
						|
        try {
 | 
						|
            // 外网IP
 | 
						|
            String outIp = null;
 | 
						|
 | 
						|
            // 本地IP,如果没有配置外网IP则返回它
 | 
						|
            String localhostIp = null;
 | 
						|
            Enumeration<NetworkInterface> netInterfaces;
 | 
						|
            netInterfaces = NetworkInterface.getNetworkInterfaces();
 | 
						|
            InetAddress ip;
 | 
						|
            boolean flag = false; // 是否找到外网IP
 | 
						|
            while (netInterfaces.hasMoreElements() && !flag) {
 | 
						|
                NetworkInterface ni = netInterfaces.nextElement();
 | 
						|
                Enumeration<InetAddress> address = ni.getInetAddresses();
 | 
						|
                while (address.hasMoreElements()) {
 | 
						|
                    ip = address.nextElement();
 | 
						|
                    if (!ip.isSiteLocalAddress() && !ip.isLoopbackAddress() && !ip.getHostAddress().contains(":")) {// 外网IP
 | 
						|
                        outIp = ip.getHostAddress();
 | 
						|
                        flag = true;
 | 
						|
                        break;
 | 
						|
                    } else if (ip.isSiteLocalAddress() && !ip.isLoopbackAddress() && !ip.getHostAddress().contains(":")) {// 内网IP
 | 
						|
                        localhostIp = ip.getHostAddress();
 | 
						|
                    }
 | 
						|
                }
 | 
						|
            }
 | 
						|
            if (outIp != null && !"".equals(outIp)) {
 | 
						|
                resultIp = outIp;
 | 
						|
            } else {
 | 
						|
                resultIp = localhostIp;
 | 
						|
            }
 | 
						|
        } catch (Exception e) {
 | 
						|
            ErrorHelper.println(e);
 | 
						|
        }
 | 
						|
        return resultIp;
 | 
						|
    }
 | 
						|
 | 
						|
    /**
 | 
						|
     * 获取本机的外网ip地址
 | 
						|
     */
 | 
						|
    public static String getOutIP() {
 | 
						|
        String ip = "";
 | 
						|
        StringBuilder result = new StringBuilder();
 | 
						|
        HttpURLConnection urlConnection = null;
 | 
						|
        BufferedReader in = null;
 | 
						|
        try {
 | 
						|
            URL url = new URL("http://ip.chinaz.com");
 | 
						|
            urlConnection = (HttpURLConnection) url.openConnection();
 | 
						|
            in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), StandardCharsets.UTF_8));
 | 
						|
 | 
						|
            String read;
 | 
						|
            while ((read = in.readLine()) != null) {
 | 
						|
                result.append(read).append("\r\n");
 | 
						|
            }
 | 
						|
        } catch (IOException e) {
 | 
						|
            ErrorHelper.println(e);
 | 
						|
        } finally {
 | 
						|
            try {
 | 
						|
                if (urlConnection != null) {
 | 
						|
                    urlConnection.disconnect();
 | 
						|
                }
 | 
						|
                if (in != null) {
 | 
						|
                    in.close();
 | 
						|
                }
 | 
						|
            } catch (IOException e) {
 | 
						|
                ErrorHelper.println(e);
 | 
						|
            }
 | 
						|
        }
 | 
						|
        Pattern p = Pattern.compile("<dd class=\"fz24\">(.*?)</dd>");
 | 
						|
        Matcher m = p.matcher(result.toString());
 | 
						|
        if (m.find()) {
 | 
						|
            ip = m.group(1);
 | 
						|
        }
 | 
						|
        return ip;
 | 
						|
    }
 | 
						|
 | 
						|
 | 
						|
    /**
 | 
						|
     * 解析ip地址
 | 
						|
     * <p>
 | 
						|
     * 设置访问地址为http://ip.taobao.com/service/getIpInfo.php
 | 
						|
     * 设置请求参数为ip=[已经获得的ip地址]
 | 
						|
     * 设置解码方式为UTF-8
 | 
						|
     *
 | 
						|
     * @param content  请求的参数 格式为:ip=192.168.1.101
 | 
						|
     * @param encoding 服务器端请求编码。如GBK,UTF-8等
 | 
						|
     */
 | 
						|
    public static String getAddresses(String content, String encoding) throws UnsupportedEncodingException {
 | 
						|
        //设置访问地址
 | 
						|
        String urlStr = "http://ip.taobao.com/service/getIpInfo.php";
 | 
						|
        // 从http://whois.pconline.com.cn取得IP所在的省市区信息
 | 
						|
        String returnStr = getResult(urlStr, content, encoding);
 | 
						|
        if (returnStr != null) {
 | 
						|
            // 处理返回的省市区信息
 | 
						|
            // System.out.println(returnStr);
 | 
						|
            String[] temp = returnStr.split(",");
 | 
						|
            if (temp.length < 3) {
 | 
						|
                return "0";// 无效IP,局域网测试
 | 
						|
            }
 | 
						|
 | 
						|
            String country = ""; // 国家
 | 
						|
            String area = "";    // 地区
 | 
						|
            String region = "";  // 省份
 | 
						|
            String city = "";    // 市区
 | 
						|
            String county = "";  // 地区
 | 
						|
            String isp = "";     // ISP公司
 | 
						|
            for (int i = 0; i < temp.length; i++) {
 | 
						|
                switch (i) {
 | 
						|
                    case 2:
 | 
						|
                        country = (temp[i].split(":"))[1].replaceAll("\"", "");
 | 
						|
                        country = URLDecoder.decode(country, encoding);// 国家
 | 
						|
                        break;
 | 
						|
                    case 3:
 | 
						|
                        area = (temp[i].split(":"))[1].replaceAll("\"", "");
 | 
						|
                        area = URLDecoder.decode(area, encoding);// 地区
 | 
						|
                        break;
 | 
						|
                    case 4:
 | 
						|
                        region = (temp[i].split(":"))[1].replaceAll("\"", "");
 | 
						|
                        region = URLDecoder.decode(region, encoding);// 省份
 | 
						|
                        break;
 | 
						|
                    case 5:
 | 
						|
                        city = (temp[i].split(":"))[1].replaceAll("\"", "");
 | 
						|
                        city = URLDecoder.decode(city, encoding);// 市区
 | 
						|
                        if ("内网IP".equals(city)) {
 | 
						|
                            return "地址为:内网IP";
 | 
						|
                        }
 | 
						|
                        break;
 | 
						|
                    case 6:
 | 
						|
                        county = (temp[i].split(":"))[1].replaceAll("\"", "");
 | 
						|
                        county = URLDecoder.decode(county, encoding);// 地区
 | 
						|
                        break;
 | 
						|
                    case 7:
 | 
						|
                        isp = (temp[i].split(":"))[1].replaceAll("\"", "");
 | 
						|
                        isp = URLDecoder.decode(isp, encoding); // ISP公司
 | 
						|
                        break;
 | 
						|
                }
 | 
						|
            }
 | 
						|
            return "地址为:" + country + "," + region + "省," + city + "市," + county + "," + "ISP公司:" + isp;
 | 
						|
        }
 | 
						|
        return null;
 | 
						|
    }
 | 
						|
 | 
						|
 | 
						|
    /**
 | 
						|
     * 获取本机的外网ip地址
 | 
						|
     *
 | 
						|
     * @return 本机的外网ip地址
 | 
						|
     */
 | 
						|
    public String getV4IP() {
 | 
						|
        String ip = "";
 | 
						|
        String china = "http://ip.chinaz.com";
 | 
						|
 | 
						|
        StringBuilder inputLine = new StringBuilder();
 | 
						|
        HttpURLConnection urlConnection = null;
 | 
						|
        BufferedReader in = null;
 | 
						|
        try {
 | 
						|
            URL url = new URL(china);
 | 
						|
            urlConnection = (HttpURLConnection) url.openConnection();
 | 
						|
            String read;
 | 
						|
            in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), StandardCharsets.UTF_8));
 | 
						|
            while ((read = in.readLine()) != null) {
 | 
						|
                inputLine.append(read).append("\r\n");
 | 
						|
            }
 | 
						|
            //System.out.println(inputLine.toString());
 | 
						|
        } catch (IOException e) {
 | 
						|
            e.printStackTrace();
 | 
						|
        } finally {
 | 
						|
            try {
 | 
						|
                if (in != null) in.close();
 | 
						|
 | 
						|
                if (urlConnection != null) urlConnection.disconnect();
 | 
						|
            } catch (IOException e) {
 | 
						|
                e.printStackTrace();
 | 
						|
            }
 | 
						|
        }
 | 
						|
        Pattern p = Pattern.compile("<dd class=\"fz24\">(.*?)</dd>");
 | 
						|
        Matcher m = p.matcher(inputLine.toString());
 | 
						|
        if (m.find()) {
 | 
						|
            ip = m.group(1);
 | 
						|
            //System.out.println(ip);
 | 
						|
        }
 | 
						|
        return ip;
 | 
						|
    }
 | 
						|
 | 
						|
 | 
						|
 | 
						|
    /**
 | 
						|
     * 访问目标地址并获取返回值
 | 
						|
     *
 | 
						|
     * @param urlStr   请求的地址
 | 
						|
     * @param content  请求的参数 格式为:ip=192.168.1.101
 | 
						|
     * @param encoding 服务器端请求编码。如GBK,UTF-8等
 | 
						|
     */
 | 
						|
    public static String getResult(String urlStr, String content, String encoding) {
 | 
						|
        HttpURLConnection connection = null;
 | 
						|
        try {
 | 
						|
            URL url = new URL(urlStr);
 | 
						|
            connection = (HttpURLConnection) url.openConnection();// 新建连接实例
 | 
						|
            connection.setConnectTimeout(2000); // 设置连接超时时间,单位毫秒
 | 
						|
            connection.setReadTimeout(33000);   // 设置读取数据超时时间,单位毫秒
 | 
						|
            connection.setDoOutput(true); // 是否打开输出流 true|false
 | 
						|
            connection.setDoInput(true);  // 是否打开输入流true|false
 | 
						|
            connection.setRequestMethod("POST");// 提交方法POST|GET
 | 
						|
            connection.setUseCaches(false); // 是否缓存true|false
 | 
						|
            connection.connect(); // 打开连接端口
 | 
						|
            DataOutputStream out = new DataOutputStream(connection.getOutputStream()); // 打开输出流往对端服务器写数据
 | 
						|
            out.writeBytes(content); // 写数据,也就是提交你的表单 name=xxx&pwd=xxx
 | 
						|
            out.flush(); // 刷新
 | 
						|
            out.close(); // 关闭输出流
 | 
						|
            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), encoding));
 | 
						|
            // 往对端写完数据对端服务器返回数据
 | 
						|
            // 以BufferedReader流来读取
 | 
						|
            StringBuilder buffer = new StringBuilder();
 | 
						|
            String line;
 | 
						|
            while ((line = reader.readLine()) != null) {
 | 
						|
                buffer.append(line);
 | 
						|
            }
 | 
						|
            reader.close();
 | 
						|
            return buffer.toString();
 | 
						|
        } catch (IOException e) {
 | 
						|
            ErrorHelper.println(e);
 | 
						|
        } finally {
 | 
						|
            if (connection != null) {
 | 
						|
                connection.disconnect(); // 关闭连接
 | 
						|
            }
 | 
						|
        }
 | 
						|
        return null;
 | 
						|
    }
 | 
						|
 | 
						|
 | 
						|
    /**
 | 
						|
     * 弹框响应
 | 
						|
     *
 | 
						|
     * @param response 响应流
 | 
						|
     * @param data     显示内容
 | 
						|
     */
 | 
						|
    public static void outRespAlert(HttpServletResponse response, String data) {
 | 
						|
        response.setContentType("text/html; charset=UTF-8");
 | 
						|
        try {
 | 
						|
            PrintWriter out = response.getWriter();
 | 
						|
 | 
						|
            String returnVal = "";
 | 
						|
            returnVal += "<html>";
 | 
						|
            returnVal += "<head><title>提示</title></head>";
 | 
						|
            returnVal += "<body background-color=\"#fff\">";
 | 
						|
            returnVal += "<script msgInterface=\"text/javascript\">";
 | 
						|
            returnVal += "alert(\"" + data + "\");";
 | 
						|
            returnVal += "</script>";
 | 
						|
            returnVal += "</body></html>";
 | 
						|
            out.println(returnVal);
 | 
						|
        } catch (IOException ex) {
 | 
						|
            ex.printStackTrace();
 | 
						|
        }
 | 
						|
    }
 | 
						|
 | 
						|
//    /**
 | 
						|
//     * 响应success字符串
 | 
						|
//     *
 | 
						|
//     * @param resp 响应流
 | 
						|
//     */
 | 
						|
//    public static void respSuccess(HttpServletResponse resp) {
 | 
						|
//        outRespBytes(resp, "success");
 | 
						|
//    }
 | 
						|
//
 | 
						|
//    /**
 | 
						|
//     * 响应字节流
 | 
						|
//     *
 | 
						|
//     * @param resp     响应流
 | 
						|
//     * @param respData 响应数据
 | 
						|
//     */
 | 
						|
//    public static void outRespBytes(HttpServletResponse resp, String respData) {
 | 
						|
//        try (ServletOutputStream out = resp.getOutputStream()) {
 | 
						|
//            if (respData == null || "".equals(respData)) {
 | 
						|
//                respData = "success";
 | 
						|
//            }
 | 
						|
//            out.write(respData.getBytes(StandardCharsets.UTF_8));
 | 
						|
//            out.flush();
 | 
						|
//        } catch (Exception e) {
 | 
						|
//            ErrorHelper.println(e);
 | 
						|
//        }
 | 
						|
//    }
 | 
						|
 | 
						|
}
 | 
						|
 |