AddressUtils.java 1.6 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
package cn.timer.api.utils;

import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.alibaba.fastjson.JSONObject;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.Header;
import cn.hutool.http.HttpRequest;

/**
 * 获取地址类
 * 
 * @author Tang
 */
public class AddressUtils
{
	private static final Logger log = LoggerFactory.getLogger(AddressUtils.class);

    public static final String IP_URL = "http://ip.taobao.com/outGetIpInfo";
    
    public static Map<String, Object> PARAM_MAP = new HashMap<String, Object>();
    
    static {
    	PARAM_MAP.put("accessKey", "alibaba-inc");
    }

    public static String getRealAddressByIP(String ip)
    {
       	PARAM_MAP.put("ip", ip);
        String address = "XX XX";
        // 内网不查询
        if (UserIp.internalIp(ip))
        {
            return "内网IP";
        }
        //链式构建请求
    	String rspStr = HttpRequest.post(IP_URL)
    	    .header(Header.USER_AGENT, "Hutool http")//头信息,多个头信息多次调用此方法即可
    	    .form(PARAM_MAP)//表单内容
    	    .timeout(20000)//超时,毫秒
    	    .execute().body();
        if (StrUtil.isEmpty(rspStr))
        {
            log.error("获取地理位置异常 {}", ip);
            return address;
        }
        JSONObject obj = JSONObject.parseObject(rspStr);
        JSONObject data = obj.getObject("data", JSONObject.class);
        String region = data.getString("region");
        String city = data.getString("city");
        address = region + " " + city;
        return address;
    }
}