Android根據(jù)IP獲取位置信息(城市、經(jīng)緯度等)

最近項(xiàng)目需要用到位置信息,需要利用IP獲取到經(jīng)緯度。
網(wǎng)上的做法很多有的是通過百度api獲取到位置,缺點(diǎn)是沒有經(jīng)緯度信息,只有城市等。
這里我找到了一個(gè)鏈接可以獲取到具體的經(jīng)緯度信息的。分別將這兩個(gè)方法記錄下來(lái)。這個(gè)方法都只需傳入IP即可獲取到位置信息

public class LocationUtils {

    private static final String TAG = "LocationUtils";

    /**
     * http://ip-api.com/json/58.192.32.1?fields=520191&lang=en
     * 根據(jù)ip獲取位置信息
     *
     * @param ip
     * @return {"accuracy":50,"as":"AS4538 China Education and Research Network Center",
     * "city":"Nanjing","country":"China","countryCode":"CN","isp":
     * "China Education and Research Network Center","lat":32.0617,"lon":118.7778,"mobile":false,
     * "org":"China Education and Research Network Center","proxy":false,"query":"58.192.32.1",
     * "region":"JS","regionName":"Jiangsu","status":"success","timezone":"Asia/Shanghai","zip":""}
     */
    public static JSONObject Ip2Location(String ip) {
        JSONObject jsonObject = null;

        String urlStr = "http://ip-api.com/json/" + ip + "?fields=520191&lang=en";
        try {
            URL url = new URL(urlStr);
            HttpURLConnection  urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setRequestMethod("GET");
            urlConnection.setReadTimeout(5000);//讀取超時(shí)
            urlConnection.setConnectTimeout(5000); // 連接超時(shí)
            urlConnection.setDoInput(true);
            urlConnection.setUseCaches(false);
            int responseCode = urlConnection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                //找到服務(wù)器的情況下,可能還會(huì)找到別的網(wǎng)站返回html格式的數(shù)據(jù)
                InputStream is = urlConnection.getInputStream();

                BufferedReader buff = new BufferedReader(new InputStreamReader(is, "UTF-8"));//注意編碼,會(huì)出現(xiàn)亂碼
                StringBuilder builder = new StringBuilder();
                String line = null;
                while ((line = buff.readLine()) != null) {
                    builder.append(line);
                }
                buff.close();//內(nèi)部會(huì)關(guān)閉InputStream
                urlConnection.disconnect();

                String res = builder.toString();

                Log.i(TAG, "Ip2Location: res -- "+res);
                if (StringUtils.isJSONString(res)){
                    jsonObject = new JSONObject(res);

                }
            }


        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ProtocolException e) {
            e.printStackTrace();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return jsonObject;
    }


    /**
     * 根據(jù)ip通過百度api去獲取城市
     * @param ip
     * @return
     */
    public static String Ip2LocationByBaiduApi(String ip){
        try {
            URL url = new URL("http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=json&ip=" + ip);
            URLConnection connection = url.openConnection();
            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(),"utf-8"));
            String line = null;
            StringBuffer res = new StringBuffer();
            while ((line = reader.readLine())!=null){
                res.append(line);
            }
            reader.close();
            String ipAddr = res.toString();
            if (StringUtils.isJSONString(ipAddr)){
                JSONObject jsonObject = new JSONObject(ipAddr);
                if ("1".equals(jsonObject.get("ret").toString())){
                    return jsonObject.get("city").toString();
                }else {
                    return "讀取失敗";
                }

            }else {
                return "訪問后得到的不是json數(shù)據(jù), res -- "+ipAddr;
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
            return "讀取失敗 e -- "+e.getMessage();
        } catch (IOException e) {
            e.printStackTrace();
            return "讀取失敗 e -- "+e.getMessage();
        } catch (JSONException e) {
            e.printStackTrace();
            return "讀取失敗 e -- "+e.getMessage();
        }
    }
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

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