您的位置:首页 > 其它

根据ip解析相应的地址,调用淘宝接口

2017-03-05 13:59 671 查看
package org.util;

import java.io.BufferedReader;

import java.io.InputStreamReader;

import java.net.URL;

import java.net.URLConnection;

import java.util.Collections;

import java.util.HashMap;

import java.util.List;

import java.util.Map;

import org.apache.log4j.Logger;

import org.isli.deal.resolution.pojo.AreaInfo;

/**

 * 根据ip 解析取到相应的地址

 * 

 * @author 

 *

 */

public class AddressUtil {

    private static final Logger LOGGER = Logger

            .getLogger(KafkaConsumerUtil.class);

    private static final String ANALYSIS_IP_URL = "http://ip.taobao.com/service/getIpInfo.php";

    private static Map<String, AreaInfo> addressMap = Collections

            .synchronizedMap(new HashMap<String, AreaInfo>());

    /**

     * IP转换成地址

     * 

     * @param ip

     * @return

     */

    public AreaInfo getAddressByIp(String ip) {

        LOGGER.info("===param..." + ip);

        AreaInfo area = null;

        try {

            if (null != ip && !"".equals(ip)) {

                // 超过20000条,清缓存

                if (addressMap.size() > ConstantNumber.TWENTY_THOUSAND) {

                    addressMap.clear();

                }

                area = addressMap.get(ip);

                if (null == area) {

                    area = getAddresses(ip, "UTF-8");

                    if (null != area) {

                        addressMap.put(ip, area);

                    }

                }

            }

        } catch (Exception e) {

            LOGGER.info("[AddressUtil.getAddressByIp]" + e.getMessage());

        }

        return area;

    }

    /**

     * 

     * @param ip

     *            请求的参数 格式为:183.16.9.216

     * @param encoding

     *            服务器端请求编码。如GBK,UTF-8等

     * @return

     * @throws Exception

     */

    public AreaInfo getAddresses(String ip, String encodingString)

            throws Exception {

        AreaInfo areaInfo = null;

        try {

            // 取得IP所在的国家省市信息

            String returnStr = getResult(ANALYSIS_IP_URL, ip, encodingString);

            if (null != returnStr && !"".equals(returnStr)) {

                // 处理返回的省市区信息

                LOGGER.info(returnStr);

                String[] temp = returnStr.split(",");

                if (temp.length > ConstantNumber.NUM_EIGHT) {

                    areaInfo = new AreaInfo();

                    String countryId = (temp[2].split(":"))[1].replaceAll("\"",

                            "");

                    String country = "";

                    String province = "";

                    String city = "";

                    if ("IANA".equals(countryId)) {

                        // 表示内网

                        country = "中国";

                        province = "广东省";

                        city = "深圳市";

                    } else {

                        // 国家1

                        country = (temp[1].replaceAll("\\:\\{", "")

                                .split(":"))[1].replaceAll("\"", "");

                        country = decodeUnicode(country);

                        // 省份5

                        province = (temp[ConstantNumber.NUM_FIVE].split(":"))[1]

                                .replaceAll("\"", "");

                        province = decodeUnicode(province);

                        // 城市7

                        city = (temp[ConstantNumber.NUM_SEVEN].split(":"))[1]

                                .replaceAll("\"", "");

                        city = decodeUnicode(city);

                    }

                    LOGGER.info("country=" + country + ",province=" + province

                            + ",city=" + city);

                    areaInfo.setCountry(country);

                    areaInfo.setProvince(province);

                    areaInfo.setCity(city);

                }

            }

        } catch (Exception e) {

            LOGGER.info("[AddressUtil.getAddresses]" + e);

            e.printStackTrace();

        }

        return areaInfo;

    }

    /**

     * @param urlStr

     *            请求的地址

     * @param ip

     *            请求的参数 格式为:183.16.9.216

     * @param encoding

     *            服务器端请求编码。如GBK,UTF-8等

     * @return

     */

    private String getResult(String urlStr, String ip, String encoding) {

        String result = "";

        BufferedReader in = null;

        try {

            String urlNameString = urlStr + "?ip=" + ip;

            URL realUrl = new URL(urlNameString);

            // 打开和URL之间的连接

            URLConnection connection = realUrl.openConnection();

            // 设置通用的请求属性

            connection.setRequestProperty("accept", "*/*");

            connection.setRequestProperty("connection", "Keep-Alive");

            connection.setRequestProperty("user-agent",

                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");

            // 建立实际的连接

            connection.connect();

            // 获取所有响应头字段

            Map<String, List<String>> map = connection.getHeaderFields();

            // 遍历所有的响应头字段

            for (String key : map.keySet()) {

                LOGGER.info(key + "--->" + map.get(key));

            }

            // 定义 BufferedReader输入流来读取URL的响应

            in = new BufferedReader(

                    new InputStreamReader(connection.getInputStream()));

            String line;

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

                result += line;

            }

        } catch (Exception e) {

            LOGGER.info("发送GET请求出现异常!" + e);

            e.printStackTrace();

        } finally {

            // 使用finally块来关闭输入流

            try {

                if (in != null) {

                    in.close();

                }

            } catch (Exception e2) {

                e2.printStackTrace();

            }

        }

        LOGGER.info("[AddressUtil.getResult]" + result);

        return result;

    }

    /**

     * unicode 转换成 中文

     * 

     * @param theString

     * @return

     */

    public static String decodeUnicode(String theString) {

        char aChar;

        int len = theString.length();

        StringBuffer outBuffer = new StringBuffer(len);

        for (int x = 0; x < len;) {

            aChar = theString.charAt(x++);

            if (aChar == '\\') {

                aChar = theString.charAt(x++);

                if (aChar == 'u') {

                    int value = 0;

                    for (int i = 0; i < ConstantNumber.NUM_FOUR; i++) {

                        aChar = theString.charAt(x++);

                        switch (aChar) {

                            case '0':

                            case '1':

                            case '2':

                            case '3':

                            case '4':

                            case '5':

                            case '6':

                            case '7':

                            case '8':

                            case '9':

                                value = (value << ConstantNumber.NUM_FOUR)

                                        + aChar - '0';

                                break;

                            case 'a':

                            case 'b':

                            case 'c':

                            case 'd':

                            case 'e':

                            case 'f':

                                value = (value << ConstantNumber.NUM_FOUR)

                                        + ConstantNumber.NUM_TEN + aChar - 'a';

                                break;

                            case 'A':

                            case 'B':

                            case 'C':

                            case 'D':

                            case 'E':

                            case 'F':

                                value = (value << ConstantNumber.NUM_FOUR)

                                        + ConstantNumber.NUM_TEN + aChar - 'A';

                                break;

                            default:

                                throw new IllegalArgumentException(

                                        "[AddressUtil.decodeUnicode]Malformed encoding");

                        }

                    }

                    outBuffer.append((char) value);

                } else {

                    if (aChar == 't') {

                        aChar = '\t';

                    } else if (aChar == 'r') {

                        aChar = '\r';

                    } else if (aChar == 'n') {

                        aChar = '\n';

                    } else if (aChar == 'f') {

                        aChar = '\f';

                    }

                    outBuffer.append(aChar);

                }

            } else {

                outBuffer.append(aChar);

            }

        }

        return outBuffer.toString();

    }

    // 测试

    public static void main(String[] args) {

        AddressUtil addressUtils = new AddressUtil();

        // 测试ip 183.16.9.216 中国广东深圳 电信

        String ip = "183.16.9.216";

        try {

            AreaInfo area = addressUtils.getAddressByIp(ip);

            if (null != area) {

                LOGGER.info(area.getCountry() + "," + area.getProvince() + ","

                        + area.getCity());

            }

        } catch (Exception e) {

            e.printStackTrace();

        }

    }

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: