jiangping
2025-01-06 7c5484cc1169aa6ef55c77c70f136a781469a7c3
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
package com.doumee.core.utils;
 
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
 
import java.io.Serializable;
import java.nio.charset.Charset;
 
/**
 * 地区工具类
 * 第三方服务:http://whois.pconline.com.cn/
 * @author Eva.Caesar Liu
 * @date 2023/03/21 14:49
 */
@Slf4j
public class Location {
 
    // 地区API
    private static final String GET_LOCATION_API = "http://whois.pconline.com.cn/ipJson.jsp?json=true&ip=%s";
 
    /**
     * 获取地区
     * @param ip IP
     *
     * @return Info
     */
    public Info getLocation (String ip) {
        try {
            return Utils.Http.build(String.format(GET_LOCATION_API, ip), Charset.forName("GBK").toString())
                    .setRequestProperty("Accept-Language", "zh-CN,zh;q=0.9")
                    .setRequestProperty("Accept-Encoding", "gzip, deflate")
                    .gzip()
                    .get()
                    .toClass(Info.class);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return null;
    }
 
    /**
     * 获取地区
     * @param ip IP
     *
     * @return String
     */
    public String getLocationString (String ip) {
        Info info = this.getLocation(ip);
        if (info == null) {
            return "UNKNOWN";
        }
        return info.getAddr();
    }
 
    /**
     * 地区信息包装
     */
    @Data
    public static class Info implements Serializable {
 
        private String pro;
 
        private String proCode;
 
        private String city;
 
        private String cityCode;
 
        private String addr;
 
    }
}