IPTools.java
1.23 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?format=json&";
public static Location getLocationWithIP(String IP) {
try {
Map<String, String> params = new HashMap<String, String>();
params.put("ip",IP);
String url = sinaIPGetter + URLEncoder.encode(IP, "utf-8");
String content = HttpTools.requestByMap(url, "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 (UnsupportedEncodingException e) {
e.printStackTrace();
return null;
}
}
}