通过IP地址获取地理位置信息

这里我用的阿里淘宝的接口

http://ip.taobao.com/service/getIpInfo.php?ip=218.201.8.37(已失效)

2020年后更新的最新的接口:http://ip.taobao.com/outGetIpInfo?ip=[ip地址字串]&accessKey=[访问密匙]
先看看淘宝IP地址库

http://ip.taobao.com/instructions.html
在这里插入图片描述

直接在地址栏输入淘宝接口url请求一下看看效果:
http://ip.taobao.com/outGetIpInfo?ip=218.201.8.37&&accessKey=alibaba-inc

{
    "data":{
        "area":"",
        "country":"中国",
        "isp_id":"100025",
        "queryIp":"218.201.8.37",
        "city":"重庆",
        "ip":"218.201.8.37",
        "isp":"移动",
        "county":"",
        "region_id":"500000",
        "area_id":"",
        "county_id":null,
        "region":"重庆",
        "country_id":"CN",
        "city_id":"500100"
    },
    "msg":"query success",
    "code":0
}

如下测试基于SpringBoot,但是原理都一样

导入fastjson依赖处理json:

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.51</version>
</dependency>

创建工具类AddressUtils :

package com.bhy702.website.common.util;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class AddressUtils {
  
    public static String getAddresses(String content, String encodingString){
        //调用淘宝API
        String urlStr = "http://ip.taobao.com/outGetIpInfo";
        String returnStr = getResult(urlStr, content,encodingString);
        if(returnStr != null){
            return  returnStr;
        }
        return null;
    }

    /**
     * @param urlStr
     *            请求的地址
     * @param content
     *            请求的参数 格式如:ip=xxx.xxx.xxx.xxx
     * @param encodingString
     *            服务器端请求编码。如GBK,UTF-8等
     * @return
     */
    private static String getResult(String urlStr, String content, String encodingString) {
        URL url = null;
        HttpURLConnection connection = null;
        try {
            url = new URL(urlStr);
            // 新建连接实例
            connection = (HttpURLConnection) url.openConnection();
            // 设置连接超时时间,单位毫秒
            connection.setConnectTimeout(2000);
            // 设置读取数据超时时间,单位毫秒
            connection.setReadTimeout(2000);
            //是否打开输出流
            connection.setDoOutput(true);
            //是否打开输入流
            connection.setDoInput(true);
            //提交方法 POST|GET
            connection.setRequestMethod("POST");
            //是否缓存
            connection.setUseCaches(false);
            //打开连接端口
            connection.connect();
            //打开输出流往对端服务器写数据
            DataOutputStream out = new DataOutputStream(connection.getOutputStream());
            //写数据,即提交表单 name=xxx&pwd=xxx
            out.writeBytes(content);
            //刷新
            out.flush();
            //关闭输出流
            out.close();
            // 往对端写完数据对端服务器返回数据 ,以BufferedReader流来读取
            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), encodingString));
            StringBuffer buffer = new StringBuffer();
            String line = "";
            while ((line = reader.readLine()) != null){
                buffer.append(line);
            }
            reader.close();
            return buffer.toString();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(connection != null){
                connection.disconnect();
            }
        }
        return null;
    }
}

调用工具类AddressUtils查询ip地理位置信息:

package com.bhy702.website;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bhy702.website.common.util.AddressUtils;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest
public class WebsiteApplicationTests {

    // 测试类
    @Test
    public void getAddressByIp(){
        // 参数ip
        String ip = "218.201.8.37";
        // json_result用于接收返回的json数据
        String json_result = null;
        try {
            json_result = AddressUtils.getAddresses("ip=" + ip + "&accessKey=alibaba-inc", "utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
        //使用fastjson处理json数据
        JSONObject json = JSON.parseObject(json_result);
        if(json != null) {
            String country = json.getJSONObject("data").get("country").toString();
            //String area= json.getJSONObject("data").get("area").toString();
            String province = json.getJSONObject("data").get("region").toString();
            String city = json.getJSONObject("data").get("city").toString();
            //String county= json.getJSONObject("data").get("county").toString();
            String isp = json.getJSONObject("data").get("isp").toString();


            System.out.println("国家: " + country);
            //System.out.println("地区: " + area);
            System.out.println("省份: " + province);
            System.out.println("城市: " + city);
            //System.out.println("区/县: " + county);
            System.out.println("互联网服务提供商: " + isp);

        }else{
            System.out.println("数据为null");
        }
    }
}

运行结果:
在这里插入图片描述


欢迎访问本文的个人博客链接: https://br-bai.github.io/2019/01/21/通过IP地址获取地理位置信息/

  • 4
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值