一招教你獲取當前ip地址與所處城市

最近在做項目的登錄日志模塊,需要把當前用戶登錄的ip地址與所處城市寫入到數(shù)據(jù)庫中,因此在這里我分享一下如何調(diào)用API接口

一,獲取本機ip地址

注意:這里指的是公網(wǎng)的IP地址,而不是局域網(wǎng)的IP地址,之前因為我是在學校,所以獲取的本機IP是經(jīng)過校園再分配的地址,不是公網(wǎng)的IP地址,導致定位失敗。所以我們需要用到IP查詢接口,之前用的是:http://ip.chinaz.com這個網(wǎng)址的接口,現(xiàn)在好像不能用了,于是又換了一個IP查詢接口:http://whois.pconline.com.cn/。

我們用URL資源定位符進行資源的拉取,然后利用正則表達式匹配我們想要的內(nèi)容,這樣便可以拿到我們本機的公網(wǎng)IP地址。

二,根據(jù)IP獲取地理位置

當我們拿到本機的公網(wǎng)IP后,就可以使用接口來查詢對應IP的地理位置了。我調(diào)用的是百度的ip定位api服務,詳情參見:
http://api.map.baidu.com/lbsapi/cloud/ip-location-api.htm

測試代碼

package com.oa.utils;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class getLocationANDIp {


    private static String readAll(BufferedReader rd) throws IOException {
        StringBuilder sb = new StringBuilder();
        int cp;
        while ((cp = rd.read()) != -1) {
            sb.append((char) cp);
        }
        return sb.toString();
    }


    public static JSONObject readJsonFromUrl(String url) throws IOException, JSONException {
        InputStream is = new URL(url).openStream();
        try {
            BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
            String jsonText = readAll(rd);
            JSONObject json = new JSONObject(jsonText);
            return json;
        } finally {
            is.close();
        }
    }

    public Map<String,Object> getAddress() {
        String ip = "";
        // 這個網(wǎng)址似乎不能了用了
        // String chinaz = "http://ip.chinaz.com";
        // 改用了太平洋的一個網(wǎng)址
        String chinaz = "http://whois.pconline.com.cn/";

        StringBuilder inputLine = new StringBuilder();
        String read = "";
        URL url = null;
        HttpURLConnection urlConnection = null;
        BufferedReader in = null;

        Map<String,Object> map = new HashMap<>();
        try {
            url = new URL(chinaz);
            urlConnection = (HttpURLConnection) url.openConnection();
            // 如有亂碼的,請修改相應的編碼集,這里是 gbk
            in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), "gbk"));
            while ((read = in.readLine()) != null) {
                inputLine.append(read + "\r\n");
            }
            // System.out.println(inputLine.toString());
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        // 這個是之前的正則表達式,
        // Pattern p = Pattern.compile("\\<dd class\\=\"fz24\">(.*?)\\<\\/dd>");
        // 通過正則表達式匹配我們想要的內(nèi)容,根據(jù)拉取的網(wǎng)頁內(nèi)容不同,正則表達式作相應的改變
        Pattern p = Pattern.compile("顯示IP地址為(.*?)的位置信息");
        Matcher m = p.matcher(inputLine.toString());
        if (m.find()) {
            String ipstr = m.group(0);
            // 這里根據(jù)具體情況,來截取想要的內(nèi)容
            ip = ipstr.substring(ipstr.indexOf("為") + 2, ipstr.indexOf("的") - 1);
            System.out.println(ip);
            map.put("ip",ip);
        }
        JSONObject json = null;
        try {
            // 這里調(diào)用百度的ip定位api服務 詳見 http://api.map.baidu.com/lbsapi/cloud/ip-location-api.htm
            json = readJsonFromUrl("http://api.map.baidu.com/location/ip?ak=百度密鑰&ip=" + ip);
            System.out.println(json);
            //city = (((JSONObject) ((JSONObject) json.get("content")).get("address_detail")).get("city")).toString();
            map.put("address",((JSONObject) json.get("content")).get("address").toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }

    public static void main(String[] args){
        getLocationANDIp getLocationANDIp = new getLocationANDIp();
        Map<String,Object> map =getLocationANDIp.getAddress();
        System.out.println(map.get("ip"));
        System.out.println(map.get("address"));
    }
}

上面這個類只需要導入一個json的jar包就可以,在maven項目的pom.xml文件中添加如下依賴:

   <dependency>
        <groupId>org.json</groupId>
        <artifactId>json</artifactId>
        <version>20090211</version>
  </dependency>

運行效果:


結(jié)果
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

友情鏈接更多精彩內(nèi)容