根据IP地址查询

      最近公司用到了根据用户的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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值