根據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


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章