java获取ip工具类

package com.hxzx.utils;

import com.alibaba.fastjson.JSONObject;
import com.hxzx.dto.IPInfoTdo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Slf4j
public class IPUtils {

    /**
     * 获取IP地址
     *
     * 使用Nginx等反向代理软件, 则不能通过request.getRemoteAddr()获取IP地址
     * 如果使用了多级反向代理的话,X-Forwarded-For的值并不止一个,而是一串IP地址,X-Forwarded-For中第一个非unknown的有效IP字符串,则为真实IP地址
     */
    public static String getIpAddr(HttpServletRequest request) {
        String ip = null;
        try {
            ip = request.getHeader("x-forwarded-for");
            if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("Proxy-Client-IP");
            }
            if (StringUtils.isBlank(ip) || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("WL-Proxy-Client-IP");
            }
            if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("HTTP_CLIENT_IP");
            }
            if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("HTTP_X_FORWARDED_FOR");
            }
            if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getRemoteAddr();
            }
        } catch (Exception e) {
            log.error("IPUtils ERROR ", e);
        }

        //使用代理,则获取第一个IP地址
        if (StringUtils.isNotBlank(ip) && ip.contains(",")) {
            return ip.split(",")[0];
        } else {
            return ip;
        }
    }

    /**
     * 获取请求类型(是否ajax)
     * @param request
     * @return
     */
    public static String getRequestType(HttpServletRequest request){
        if (request.getHeader("x-requested-with") != null
                && request.getHeader("x-requested-with").equalsIgnoreCase("XMLHttpRequest")) {
            return "Ajax";
        }else{
            return "SyncRequest";
        }
    }

    /**
     * 获取主机外网IP
     * @return
     */
    public static String getV4IP() {
        String ip = "";
        String chinaz = "http://ip.chinaz.com/";

        String inputLine = "";
        String read = "";
        try {
            URL url = new URL(chinaz);
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
            while ((read = in.readLine()) != null) {
                inputLine += read;
            }

        } catch (Exception e) {
            // e.printStackTrace();
        }

        Pattern p = Pattern.compile("\\<dd class\\=\"fz24\">(.*?)\\<\\/dd>");
        Matcher m = p.matcher(inputLine);
        if(m.find()){
            String ipstr = m.group(1);
            System.out.println(ipstr);
        }
        return ip;
    }

    public static IPInfoTdo getIPInfo(String ip)
    {
        IPInfoTdo dto = new IPInfoTdo();
        try
        {
            String url1 = "http://api.map.baidu.com/location/ip?ak=iTrwV0ddxeFT6QUziPQh2wgGofxmWkmg";
            String result1="";
            result1 = getRs(url1, "ip="+ip, "utf-8");
            JSONObject jsonObj1 = JSONObject.parseObject(result1);
            String status = jsonObj1.getString("status").toString();
            if ("0".equals(status)) {
                JSONObject content = ((JSONObject) jsonObj1).getJSONObject("content");
                JSONObject detail = ((JSONObject) content).getJSONObject("address_detail");

                dto.setIp(ip);
                dto.setCountry("中国");//国家
                dto.setArea(CommonUtils.checkNull(detail.get("district")));//区域
                dto.setRegion(CommonUtils.checkNull(detail.get("province")));//省份
                dto.setCity(CommonUtils.checkNull(detail.get("city")));//市区
                dto.setCounty(CommonUtils.checkNull(detail.get("street")));//地区
                JSONObject point = ((JSONObject) content).getJSONObject("point");
                dto.setGPS("x:" + point.getString("x") + ",y:" + point.getString("y"));

            } else {
                String result = null;
                String url = "http://ip.taobao.com/service/getIpInfo.php";//请求接口地址
                result = getRs(url, "ip="+ip, "utf-8");
                JSONObject jsonObj = JSONObject.parseObject(result);
                if ( jsonObj != null && jsonObj.get("code").equals(0))
                {
                    JSONObject subJsonObj = jsonObj.getJSONObject("data");
                    dto = new IPInfoTdo();

                    dto.setIp(CommonUtils.checkNull(subJsonObj.get("ip")));
                    dto.setCountry(
                            CommonUtils.checkNull(subJsonObj.get("country")));//国家
                    dto.setArea(CommonUtils.checkNull(subJsonObj.get("area")));//区域
                    dto.setRegion(CommonUtils.checkNull(subJsonObj.get("region")));//省份
                    dto.setCity(CommonUtils.checkNull(subJsonObj.get("city")));//市区
                    dto.setCounty(CommonUtils.checkNull(subJsonObj.get("county")));//地区
                    dto.setIsp(CommonUtils.checkNull(subJsonObj.get("isp")));//运营商
                }
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }

        return dto;
    }


    /**
     * 从url获取结果
     *
     * @param path
     * @param params
     * @param encoding
     * @return
     */
    public static String getRs(String path, String params, String encoding) {

        URL url = null;

        HttpURLConnection connection = null;

        try {

            url = new URL(path);

            connection = (HttpURLConnection) url.openConnection();// 新建连接实例

            connection.setConnectTimeout(2000);// 设置连接超时时间,单位毫S?

            connection.setReadTimeout(2000);// 设置读取数据超时时间,单位毫S?

            connection.setDoInput(true);// 是否打开输出S? true|false

            connection.setDoOutput(true);// 是否打开输入流true|false

            connection.setRequestMethod("POST");// 提交方法POST|GET

            connection.setUseCaches(false);// 是否缓存true|false

            connection.connect();// 打开连接端口

            DataOutputStream out = new DataOutputStream(
                    connection.getOutputStream());

            out.writeBytes(params);

            out.flush();

            out.close();

            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    connection.getInputStream(), encoding));

            StringBuffer buffer = new StringBuffer();

            String line = "";

            while ((line = reader.readLine()) != null) {

                buffer.append(line);

            }

            reader.close();

            return buffer.toString();

        } catch (Exception e) {

            e.printStackTrace();

        } finally {

            connection.disconnect();// 关闭连接

        }

        return null;
    }


}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值