package kl.comm.tools;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import org.json.JSONException;
import org.json.JSONObject;
public class Ip2LocationViaBaidu {
/**
* @param ip
* 查询的地址
* @return status
* 0:正常
* 1:API查询失败
* 2:API返回数据不完整
* @throws IOException
* @throws JSONException
*/
public static Object[] getLocation(String ip) throws IOException, JSONException {
String lng = null;// 经度
String lat = null;// 纬度
String city = null;// 城市名
String status = "0";// 成功
String ipString = null;
String jsonData = ""; // 请求服务器返回的json字符串数据
try {
ipString = java.net.URLEncoder.encode(ip, "UTF-8");
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}
String key = "*************";// 百度密钥(AK)
String url = String.format("http://api.map.baidu.com/location/ip?ak=%s&ip=%s&coor=bd09ll", key, ipString);// 百度普通IP定位API
URL myURL = null;
URLConnection httpsConn = null;
try {
myURL = new URL(url);
} catch (MalformedURLException e) {
e.printStackTrace();
}
InputStreamReader insr = null;
BufferedReader br = null;
try {
httpsConn = (URLConnection) myURL.openConnection();// 不使用代理
if (httpsConn != null) {
insr = new InputStreamReader(httpsConn.getInputStream(), "UTF-8");
br = new BufferedReader(insr);
String data = null;
int count = 1;
while ((data = br.readLine()) != null) {
jsonData += data;
}
JSONObject jsonObj = new JSONObject(jsonData);
if ("0".equals(jsonObj.getString("status"))) {
city = jsonObj.getJSONObject("content").getJSONObject("address_detail").getString("city");
lng = jsonObj.getJSONObject("content").getJSONObject("point").getString("x");
lat = jsonObj.getJSONObject("content").getJSONObject("point").getString("y");
if (city.isEmpty() || lng.isEmpty() || lat.isEmpty()) {
status = "2";// API返回数据不完整
}
} else {
status = "1";// API查询失败
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (insr != null) {
insr.close();
}
if (br != null) {
br.close();
}
}
return new Object[] { status, city, lng, lat };
}
}
把上边的百度密钥换成你自己的,下边是API返回的json数据格式。
{
address: "CN|北京|北京|None|CHINANET|1|None", #地址
content: #详细内容
{
address: "北京市", #简要地址
address_detail: #详细地址信息
{
city: "北京市", #城市
city_code: 131, #百度城市代码
district: "", #区县
province: "北京市", #省份
street: "", #街道
street_number: "" #门址
},
point: #当前城市中心点
{
x: "116.39564504",
y: "39.92998578"
}
},
status: 0 #返回状态码
}