IPTools.java 1.18 KB
package com.xkl.tools;

import com.alibaba.fastjson.JSONObject;
import com.xkl.domain.Location;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by zhaoyue on 2017/4/15.
 */
public class IPTools {
    public static final String sinaIPGetter = "http://int.dpool.sina.com.cn/iplookup/iplookup.php";

    public static Location getLocationWithIP(String IP) {
        try {
            Map<String, String> params = new HashMap<String, String>();
            params.put("ip", IP);
            params.put("format", "json");

            String content = HttpTools.requestByMap(sinaIPGetter, "POST", params);
            JSONObject ipJson = JSONObject.parseObject(content);
            String country = ipJson.getString("country");
            String province = ipJson.getString("province");
            String city = ipJson.getString("city");
            String district = ipJson.getString("district");
            Location location = new Location(country, province, city, district);
            return location;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

}