Java封装阿里云通过ip来定位当前地址

1.首先去申请阿里云的ip定位的应用

在这里插入图片描述

2.找到我们需要的应用

在这里插入图片描述

3.我们来申请这个

在这里插入图片描述

4.在maven项目中配置
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.70</version>
</dependency>

5.编写代码
package cloud.zxy.system.auth.config;


import cloud.zxy.system.auth.wxconfig.HttpUtils;
import cloud.zxy.system.util.globalException.SystemServiceException;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;

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

@Component
public class IpLocationService {


    public Map<String, Object> getPositioning(String ip) {
        String host = "http://iploc.market.alicloudapi.com";
        String path = "/v3/ip";
        String method = "GET";
        ###注意这里需要填写你申请好的 AppCode
        String appcode = "你自己的AppCode";
        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + appcode);
        Map<String, String> querys = new HashMap<String, String>();
        querys.put("ip", ip);
        try {
            HttpResponse response = HttpUtils.doGet(host, path, method, headers, querys);
            String s = EntityUtils.toString(response.getEntity());
            JSONObject parse = JSONObject.parseObject(s);
            Map<String, Object> objectMap = new HashMap<>();
            BeanUtils.copyProperties(parse, objectMap);
            objectMap.put("province", parse.get("province"));
            objectMap.put("city", parse.get("city"));
            objectMap.put("infocode", parse.get("infocode"));
            objectMap.put("rectangle", parse.get("rectangle"));
            objectMap.put("status", parse.get("status"));
            objectMap.put("info", parse.get("info"));
            return objectMap;
        } catch (Exception e) {
            e.printStackTrace();
            throw new SystemServiceException("请求错误", e.getMessage());
        }
    }


}

6.测试代码
public static void main(String[] args) {
        IpLocationService service = new IpLocationService();
        Map<String, Object> map = service.getPositioning("114.247.50.2");
        System.out.println("map = " + map);
    }

在这里插入图片描述

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

往日时光--

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值