1.首先去申请阿里云的ip定位的应用
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/7626280c712dcd5fa0e1dee07b23c350.png)
2.找到我们需要的应用
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/fe7a7f6c0cfbe3e78d3cfe9e8c7a1f63.png)
3.我们来申请这个
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/1015572176047070f50741ae4c1dc958.png)
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>();
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);
}
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/8eb3269c3deab0d504a7e017862aece7.png)