js根據IP地址獲取當前的省市

思而行at空空發表於2018-06-11

3.阿里巴巴提供了介面,但不支援js跨域請求回撥,我們可以在java程式碼中請求,返回引數:

//工具類
public class ResponseUtil {

    public static void write(HttpServletResponse response,Object o)throws Exception{
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out=response.getWriter();
        out.println(o.toString());
        out.flush();
        out.close();
    }

}



import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;
import java.util.concurrent.Callable;


public class IPLocationTask implements Callable<Map<String, String>>  {


	private String id;
	private String uri;
	private String type;
	
	public IPLocationTask(String id,String type, String url) {
		super();
		this.id = id;
		this.uri = url;
		this.type = type;
	}

	@Override
	public Map<String, String> call() throws Exception {
		URL url=new URL(uri);
        HttpURLConnection conn = (HttpURLConnection)url.openConnection();  
        conn.setReadTimeout(10*1000);  
        conn.setRequestMethod("GET");  
          
        InputStreamReader  inStream = new InputStreamReader(conn.getInputStream(),"UTF-8");  
        BufferedReader buffer=new BufferedReader(inStream);  
           
        String inputline=null;
        String info="";
		while((inputline=buffer.readLine())!=null){  
            info+=inputline;  
        }  
		System.out.println(type+"=="+info);
		return IPLocationParseUtil.parse(type, info);
	}
	
}
	private String id;
	private String uri;
	private String type;
	
	public IPLocationTask(String id,String type, String url) {
		super();
		this.id = id;
		this.uri = url;
		this.type = type;
	}

	@Override
	public Map<String, String> call() throws Exception {
		URL url=new URL(uri);
        HttpURLConnection conn = (HttpURLConnection)url.openConnection();  
        conn.setReadTimeout(10*1000);  
        conn.setRequestMethod("GET");  
          
        InputStreamReader  inStream = new InputStreamReader(conn.getInputStream(),"UTF-8");  
        BufferedReader buffer=new BufferedReader(inStream);  
           
        String inputline=null;
        String info="";
		while((inputline=buffer.readLine())!=null){  
            info+=inputline;  
        }  
		System.out.println(type+"=="+info);
		return IPLocationParseUtil.parse(type, info);
	}
	
}

 

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;

import com.alibaba.fastjson.JSON;

public class IPLocationParseUtil {
    /**
     * 解析 各ip查詢提供 服務的返回結果
     * @param type
     * @param result
     * @return
     */
    public static Map<String, String> parse(String type,String result){
        
        if(StringUtils.isEmpty(result)){
            Map<String, String> error=new HashMap<String, String>();
            error.put("status", "error");
            error.put("msg", "exception");
            return error;
        }
        
        Map<String, String> map=new HashMap<String, String>();
        map.put("type", type);
        switch (type) {
        case "taobao":
            //{"code":0,"data":{"country":"\u4e2d\u56fd","country_id":"CN","area":"\u897f\u5317","area_id":"600000","region":"\u7518\u8083\u7701","region_id":"620000","city":"\u5170\u5dde\u5e02","city_id":"620100","county":"","county_id":"-1","isp":"\u7535\u4fe1","isp_id":"100017","ip":"42.91.160.188"}}
            Map<String, Object> obj =(Map<String, Object>) JSON.parse(result);
            if(obj!=null&&"0".equals(String.valueOf(obj.get("code")))){
                Map<String, String> data=(Map<String, String>)obj.get("data");
                map.put("status", "0");
                map.put("nation", data.get("country"));
                map.put("provice", data.get("region"));
                map.put("city", data.get("city"));
                map.put("isp", data.get("isp"));
                map.put("cityCode", data.get("city_id"));
                map.put("proviceCode", data.get("region_id"));
            }
            break;
        case "sina":
            //{"ret":1,"start":-1,"end":-1,"country":"\u4e2d\u56fd","province":"\u6d59\u6c5f","city":"\u676d\u5dde","district":"","isp":"","type":"","desc":""}
            Map<String, String> objs =(Map<String, String>) JSON.parse(result);
            if(objs!=null&&"1".equals(String.valueOf(objs.get("ret")))){
                map.put("status", "0");
                map.put("nation", objs.get("country"));
                map.put("provice", objs.get("province"));
                map.put("city", objs.get("city"));
                map.put("isp", objs.get("isp"));
                map.put("cityCode", "-1");
                map.put("proviceCode", "-1");
            }
            break;
            
        case "m126":
            //var lo="甘肅省", lc="蘭州市"; var localAddress={city:"蘭州市", province:"甘肅省"}
            String retStr=result.substring( result.indexOf("{"),result.lastIndexOf("}")+1);
            Map<String, String> objm =(Map<String, String>) JSON.parse(retStr);
            //中文亂碼,暫不解決
            break;
        case "baidu":
            //{"address":"CN|\u7518\u8083|\u5170\u5dde|None|CHINANET|0|0","content":{"address_detail":{"province":"\u7518\u8083\u7701","city":"\u5170\u5dde\u5e02","district":"","street":"","street_number":"","city_code":36},"address":"\u7518\u8083\u7701\u5170\u5dde\u5e02","point":{"y":"4284074.36","x":"11557683.25"}},"status":0}
            Map<String, Object> objb =(Map<String, Object>) JSON.parse(result);
            if(objb!=null&&"0".equals(String.valueOf(objb.get("status")))){
                map.put("status", "0");
                Map objd= (Map)objb.get("content");
                Map<String, String> detail=(Map<String, String>) objd.get("address_detail");
                map.put("nation", "中國");
                map.put("provice", detail.get("province"));
                map.put("city", detail.get("city"));
                map.put("isp", "");
                map.put("cityCode", "-1");
                map.put("proviceCode", "-1");
            }
            break;
            
        case "gaode":
            //{"status":"1","info":"OK","infocode":"10000","province":"甘肅省","city":"蘭州市","adcode":"620100","rectangle":"103.48207,35.95046134;104.0445292,36.22263808"}
            Map<String, Object> objg =(Map<String, Object>) JSON.parse(result);
            if(objg!=null&&"1".equals(String.valueOf(objg.get("status")))){
                map.put("status", "0");
                
                map.put("nation", "中國");
                map.put("provice", String.valueOf(objg.get("province")));
                map.put("city", String.valueOf(objg.get("city")));
                map.put("isp", "");
                map.put("cityCode", String.valueOf(objg.get("adcode")));
                map.put("proviceCode", String.valueOf(objg.get("adcode")).substring(0,2)+"0000");
            }
            break;
            
        case "qqmap":
            //{"status":0,"message":"query ok","result":{"ip":"42.91.5.62","location":{"lat":36.10396,"lng":103.71878},"ad_info":{"nation":"中國","province":"甘肅省","city":"蘭州市","district":"安寧區","adcode":620105}}}
            Map<String, Object> objq =(Map<String, Object>) JSON.parse(result);
            if(objq!=null&&"0".equals(String.valueOf(objq.get("status")))){
                map.put("status", "0");
                Map objd= (Map)objq.get("result");
                Map<String, String> detail=(Map<String, String>) objd.get("ad_info");
                map.put("nation", "中國");
                map.put("provice", detail.get("province"));
                map.put("city", detail.get("city"));
                map.put("isp", "");
                map.put("cityCode",detail.get("adcode"));
                map.put("proviceCode", detail.get("adcode").substring(0,2)+"0000");
            }
            break;
            
        default:
            map.put("status", "error");
            map.put("msg", "result error");
            break;
        }
        
        
        return map;
    }


@Service
public class IPGPSService {
	public static final String taobao="http://ip.taobao.com/service/getIpInfo.php?ip=";
	public static final String sina="http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=json&ip=";
	public static final String M126="http://ip.ws.126.net/ipquery?ip=";
	public static final String baidu="http://api.map.baidu.com/location/ip?ak=F45*******&ip=";
	public static final String gaode="http://restapi.amap.com/v3/ip?key=c7a9a********&ip=";
	public static final String qqmap="http://apis.map.qq.com/ws/location/v1/ip?key=WX***********&ip=";
	//對應的ak/key需要到對應的網站去申請 如:高德 http://lbs.amap.com/api/webservice/guide/api/ipconfig 
	public Map<String, String> getIpLocation(String ip){
		Map<String, String> retMap=new HashMap<String, String>();
		boolean right=true;
		
		ArrayList<Future<Map<String, String>>> results = new ArrayList<Future<Map<String, String>>>() ;//
		ExecutorService service=null;
		try {
			service = Executors.newFixedThreadPool(2);
			
			results.add(service.submit(new IPLocationTask("1", "taobao", taobao+ip)));
			results.add(service.submit(new IPLocationTask("2", "gaode", gaode+ip)));
			results.add(service.submit(new IPLocationTask("3", "qqmap", qqmap+ip)));
			do {
				Iterator<Future<Map<String, String>>> iterator = results.iterator();
				while(iterator.hasNext()){
					Future<Map<String, String>> future= iterator.next();
					if(future.isDone()){
						try {
							retMap=future.get();
						} catch (Exception e) {
						}
						if(retMap!=null&&"0".equals(retMap.get("status"))){
							right=false;
							break;
						}else{
							iterator.remove(); //失敗的移除掉
						}
					}
					if(results.size()==0){
						right=false; //全是失敗的結果
						retMap.put("status", "error");
						retMap.put("status", "all faid");
					}
				}
				
				if(results.size()<1){
					break;
				}
			} while (right);
				
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			service.shutdown();
			service=null;
		} 
		return retMap;
	}
	
	
	public static void main(String[] args) {
		Map<String, String> ret = new IPGPSService().getIpLocation("42.91.160.188");
		
		System.out.println("ret"+ret);
		for (String key : ret.keySet()) {
			System.out.println(key+"=="+ret.get(key));
		}
		
		/*for (int i = 0; i < 5; i++) {
			long t=System.currentTimeMillis();
			System.out.println(i+"costtime:"+ );
			System.out.println((System.currentTimeMillis()-t));
		}*/
	}
}


@Controller
public class WebServiceController {  
@Autowired
    IPGPSService iPGPSService;
@RequestMapping(value = "/public/ipquery/getIpInfo")
	public void getIpInfo(String ip,HttpServletRequest request,HttpServletResponse response) {
                //如果ip為空,獲取當前登陸的ip
                String cip=IPUtil.getClientIpAddr(request);
		
		if(StringUtils.isEmpty(ip)){
			ip=cip;
		}
		
		Map<String,String> resultMap=null;
		
		
		try {
			if(StringUtils.isEmpty(ip)){
				throw new Exception();
			}
			resultMap=iPGPSService.getIpLocation(ip);
			resultMap.put("cip", ip);
		} catch (Exception e) {
			resultMap=new HashMap<String, String>();
			resultMap.put("status", "0");  //失敗後預設至蘭州
			resultMap.put("nation", "中國");
			resultMap.put("provice", "甘肅省");
			resultMap.put("city", "蘭州市");
			resultMap.put("isp", "");
			resultMap.put("cityCode","620100");
			resultMap.put("proviceCode", "620000");
			resultMap.put("type", "default");
		}
		
		
		String callback=request.getParameter("callback");
		String retStr=JSON.toJSONString(resultMap);
		if(StringUtils.isNotBlank(callback)){
			retStr=callback+"("+retStr+")";
		}
		
		try {
			ResponseUtil.write(response, retStr);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}


js:客戶端呼叫java後臺

<script type="text/javascript">
    
    $(function(){
       
		var ipServer = "localhost:8080/projectweb";
	    	$.ajax({
	    		url:ipServer+"/public/ipquery/getIpInfo?callback=?",
	    		async :false,
	    		dataType:"jsonp",
	    		type:'get',
	    		success:function(data){
			       console.log(data)
			     },
			     error:function(XMLHttpRequest, textStatus, errorThrown) {
			       console.log(XMLHttpRequest.status);
			       console.log(XMLHttpRequest.readyState);
			       console.log(textStatus);
			     }
			 });
  }
</script>

data 的內容:

{"nation":"中國","city":"蘭州","cityCode":"620100","provice":"甘肅","isp":"電信","proviceCode":"620000","type":"taobao","status":"0"}

 

2.根據搜狐提供的API獲取當前的地區:

<script src="http://pv.sohu.com/cityjson?ie=utf-8"></script>

呼叫該API返回值為:

var returnCitySN = {"cip": "42.91.160.**", "cid": "620000", "cname": "甘肅省"};
$(document).ready(function(){
	var areaCode = returnCitySN["cid"]; //地區編碼
	var thisIp =  returnCitySN["cip"];  //IP
	var areaName = returnCitySN["cname"]; //只能獲取到省
	
}

 

1.根據新浪提供的API獲取:

 

<script src="http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=js"></script>

呼叫該API 返回值:

 var remote_ip_info = {"ret":1,"start":-1,"end":-1,"country":"\u4e2d\u56fd","province":"\u7518\u8083","city":"\u5170\u5dde","district":"","isp":"","type":"","desc":""};
$(document).ready(function(){	
    alert("當前地區"+remote_ip_info["province"]+"省"+remote_ip_info["city"]+"市"+remote_ip_info["district"]+"區");
}

注:新浪的暫時不能用了,請大家參考搜狐的或阿里巴巴的

 

 

 

 

 

 

 

 

 

 

 

 

相關文章