JAVA获取定位信息

通过用户IP获取用户地址信息

首先得到ip,有两种方式

第一种方式:通过jsoup从一些工具网页获取

第二种方式:通过获取用户对象信息得到

前者需要jsoup的jar包,不需要用户请求; 
后者需要用户发出请求,有request对象。

1.1 jsoup抓取ip信息

public static String getPublicIP() {
    String ip = "";
    try {
        Document doc = Jsoup.connect("http://www.ip138.com/ip2city.asp").ignoreContentType(false).get();
        Elements els = doc.select("center");
        for (org.jsoup.nodes.Element el : els) { 
                ip = el.text(); 
            }
        ip = ip.replaceAll("[^0-9.]", ""); 
        } catch (IOException e1) {
            e1.printStackTrace();
        }finally {

        }
        return ip; 
    }

1.2 request获取ip

public static String getIpAddr(HttpServletRequest request) {
            String ip = request.getHeader("x-forwarded-for");
            if(ip == null || ip.length() == 0 ||"unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("Proxy-Client-IP");
            }
            if(ip == null || ip.length() == 0 ||"unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("WL-Proxy-Client-IP");
            }
            if(ip == null || ip.length() == 0 ||"unknown".equalsIgnoreCase(ip)) {
                ip = request.getRemoteAddr();
            }
            return ip;
         }

本地启动的服务返回的是127.0.0.1;

内网访问获取的是内网IP地址;

远程访问获取到公网IP。

  1. 定义一个方法,将字符拼接成字符串
private static String readAll(Reader rd) throws IOException {
        StringBuilder sb = new StringBuilder();
        int cp;
        while ((cp = rd.read()) != -1) {
            sb.append((char) cp);
        }
        return sb.toString();
    }
  1. 将URL资源解析成json对象
public static JSONObject readJsonFromUrl(String url) throws IOException, JSONException {
        InputStream is = null;
        try {
            is = new URL(url).openStream();
            BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
            String jsonText = readAll(rd);
            JSONObject json = JSONObject.fromObject(jsonText);
           // System.out.println(json);
            return json;
        } finally {
            //关闭输入流
            is.close();
        }
    }
  1. 传入用户IP获取当地地址名
public static String getAddrName(String IP) throws JSONException, IOException{
        //这里调用百度的ip定位api服务 详见 http://api.map.baidu.com/lbsapi/cloud/ip-location-api.htm

        JSONObject json = readJsonFromUrl("http://api.map.baidu.com/location/ip?ak=iTrwV0ddxeFT6QUziPQh2wgGofxmWkmg&ip="+IP);
        /* 获取到的json对象:
         *         {"address":"CN|河北|保定|None|UNICOM|0|0",
         *        "content":{"address_detail":{"province":"河北省","city":"保定市","street":"","district":"","street_number":"","city_code":307},
         *        "address":"河北省保定市","point":{"x":"12856963.35","y":"4678360.5"}},
         *        "status":0}
        */
        //如果IP是本地127.0.0.1或者内网IP192.168则status分别返回1和2
        String status = json.opt("status").toString();
        if(!"0".equals(status)){
            return "";
        }
        JSONObject content=((JSONObject) json).getJSONObject("content");              //获取json对象里的content对象
        JSONObject addr_detail=((JSONObject) content).getJSONObject("address_detail");//从content对象里获取address_detail
        String city=addr_detail.opt("city").toString();                             //获取市名,可以根据具体需求更改
        return city;
    }

测试一下,所有方法都是静态的,类名getPuplic

 //String scity=getPuplic.getAddrName("218.83.245.210"); //上海IP
    String IP1 = getPuplic.getPublicIP();
    String IP2 = getPuplic.getIpAddr(request);
    String scity1=getPuplic.getAddrName(IP1);
    String scity2=getPuplic.getAddrName(IP2);
    logger.info("---------jsoup定位-------------"+scity1);
    logger.info("---------request-------------"+scity2);

用第一种方式需要引入的包

import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.select.Elements;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;

 

 

--------------------------------请多多指教

posted on 2019-08-26 10:27  不听话的M老大  阅读(1506)  评论(0编辑  收藏  举报

导航