通过ip获取真实地址

为什么80%的码农都做不了架构师?>>>   hot3.png

package util;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

import java.io.IOException;

/**
 * 根据ip获取地址
 *
 * @author kz
 */
public class AddressUtil {

    public static void main(String[] args) {
        getIpAddressTwice("119.137.52.13");
    }

    /**
     * 先通过淘宝api获取地址,如果没有获取再去从新浪获取地址
     *
     * @param ip
     * @return
     */
    public static String getIpAddressTwice(String ip) {
        String taobaoIpAddress = getIpAddressByTaoBaoAPI(ip);
        if (StringUtils.isNotEmpty(taobaoIpAddress)) {
            return taobaoIpAddress;
        }
        return getIpAddressBySinaAPI(ip);
    }

    /**
     * 淘宝获取
     *
     * @param ip
     * @return
     */
    public static String getIpAddressByTaoBaoAPI(String ip) {
        String apiUrl = "http://ip.taobao.com/service/getIpInfo.php?ip=" + ip;

        return getIpAddress(apiUrl, ip);
    }

    /**
     * 新浪获取
     *
     * @param ip
     * @return
     */
    public static String getIpAddressBySinaAPI(String ip) {
        String url = "http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=json&ip=" + ip;
        String provinceName = "", cityName = "", countryName = "", isp = "";
        StringBuilder address = new StringBuilder();
        HttpClient client = HttpClientBuilder.create().build();
        HttpGet request = new HttpGet(url);
        try {
            HttpResponse response = client.execute(request);
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode == HttpStatus.SC_OK) {
                String strResult = EntityUtils.toString(response.getEntity());
                try {

                    JSONObject jsonResult = JSON.parseObject(strResult);
                    if (jsonResult == null) {
                        return null;
                    }
                    countryName = jsonResult.getString("country");
                    provinceName = jsonResult.getString("province");
                    cityName = jsonResult.getString("city");
                    isp = jsonResult.getString("isp");
                    address.append(countryName).append(provinceName).append(cityName);
                    if (StringUtils.isNotEmpty(isp)) {
                        address.append(":").append(isp);
                    }
                    //System.out.println(JSON.toJSONString(jsonResult, true));
                    System.out.println(address);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return address.toString();
    }

    public static String getIpAddress(String apiUrl, String ip) {
        String provinceName = "", cityName = "", countryName = "", isp = "";
        StringBuilder address = new StringBuilder();
        HttpClient client = HttpClientBuilder.create().build();
        HttpGet request = new HttpGet(apiUrl);
        try {
            HttpResponse response = client.execute(request);
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode == HttpStatus.SC_OK) {
                String strResult = EntityUtils.toString(response.getEntity());
                try {
                    JSONObject jsonResult = JSON.parseObject(strResult);
                    JSONObject dataJson = jsonResult.getJSONObject("data");
                    if (dataJson == null) {
                        return null;
                    }
                    countryName = dataJson.getString("country");
                    provinceName = dataJson.getString("region");
                    cityName = dataJson.getString("city");
                    isp = jsonResult.getString("isp");
                    address.append(countryName).append(provinceName).append(cityName);
                    if (StringUtils.isNotEmpty(isp)) {
                        address.append(":").append(isp);
                    }
                    //System.out.println(JSON.toJSONString(jsonResult, true));
                    System.out.println(address);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return address.toString();
    }
}



###########################################这里附上IpUtil类#####################################



package util;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * 获取请求主机IP地址公共类.如果通过代理进来,则透过防火墙获取真实IP地址。
 * @author kz
 */
public class IpUtil {
    private final static Logger logger = LoggerFactory.getLogger(IpUtil.class);

    /**
     * 获取请求主机IP地址,如果通过代理进来,则透过防火墙获取真实IP地址;
     *
     * @param request
     * @return
     * @throws IOException
     */
    public final static String getIpAddress(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) {
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("Proxy-Client-IP");
            }
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("WL-Proxy-Client-IP");
            }
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("HTTP_CLIENT_IP");
            }
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("HTTP_X_FORWARDED_FOR");
            }
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getRemoteAddr();
            }
        } else if (ip.length() > 15) {
            String[] ips = ip.split(",");
            for (int index = 0; index < ips.length; index++) {
                String strIp = (String) ips[index];
                if (!("unknown".equalsIgnoreCase(strIp))) {
                    ip = strIp;
                    break;
                }
            }
        }
        if (logger.isInfoEnabled()) {
            logger.info("request ip:{}", ip);
        }
        return ip;
    }

}


 

转载于:https://my.oschina.net/kezhen/blog/1928184

你可能感兴趣的:(通过ip获取真实地址)