最近公司用到了根据用户的ip获取用户所在的地址,小研究一下,发现百度地图提供了很好的接口,现整理一个小demo,有需要的朋友可以看一下,也方便自己以后使用!
直接看代码吧
package com.gt.admin.web.analyticWebsite;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import net.sf.json.JSONObject;
public class City {
private final String error ="0"; // 成功状态码
private final String ak="bAc1NYYIReeoFTFtPbTOK7IxPkbPSw5a";
public Object [] getIPAddress(String ip){
Object[] obj = new Object[4];
StringBuffer sb = new StringBuffer();
BufferedReader in = null;
try {
URL url = new URL("https://api.map.baidu.com/location/ip?ak="+ak+"&ip="+ip+"&coor=bd09ll");
URLConnection connection =url.openConnection();
connection.connect();
in = new BufferedReader(new InputStreamReader(
connection.getInputStream(),"UTF-8"));
String line;
while ((line = in.readLine()) != null) {
sb.append(line);
}
//System.out.println(sb.toString());
JSONObject array= JSONObject.fromObject(sb.toString());
String status = array.getString("status");
obj[0]=status;
if(status.equals(error)){
JSONObject content= array.getJSONObject("content");
JSONObject detail = content.getJSONObject("address_detail");
String city = detail.getString("city");
String province =detail.getString("province");
String city_code=detail.getString("city_code");
obj[1]=city;
obj[2]=province;
obj[3]=city_code;
}
} catch (Exception e) {
obj[0]="-1";
e.printStackTrace();
}finally{
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return obj;
}
public static void main(String[] args) {
City lo = new City();
Object obj[]=lo.getIPAddress("114.242.2.96");
if(obj[0].toString().equals("0")){
for (int isys = 0; isys < obj.length; isys++) {
System.out.println(obj[isys].toString());
}
}
}
}
需要的jar包有:
json-lib-2.2.2-jdk15.jar
ezmorph-1.0.2.jar
commons-logging-1.1.jar
commons-lang-2.3.jar
commons-discovery-0.2.jar
commons-collections-3.1.jar
commons-codec-1.4.jar
commons-beanutils-1.8.0.jar