吉安感知网项目-后端
xiebin
2026-01-06 d207a86cdf1ab52ef8cb7cd83bad8fceab8038cf
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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
package org.sxkj.system.util;
 
import cn.hutool.core.util.ObjectUtil;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.sxkj.system.entity.Region;
import org.sxkj.system.ssl.SSL;
import javax.net.ssl.HttpsURLConnection;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
 
import static com.baomidou.mybatisplus.extension.toolkit.Db.saveBatch;
 
/**
 * 区域信息拉取 util
 */
@Slf4j
public class RegionUtil {
 
    private final static String URL = "https://www.stats.gov.cn/sj/tjbz/tjyqhdmhcxhfdm/2023/index.html";
 
 
    /**
     * 拉取统计局数据入库
     */
    public void getRegionInfoSave() {
        Boolean provinces = getProvinces(0, URL);
    }
 
    /**
     * 建立连接
     */
    private static Document connect(String url) {
        if (url == null || url.isEmpty()) {
            throw new IllegalArgumentException("无效的url");
        }
        try {
            String path = url+"?timestamp="+ System.currentTimeMillis();
            SSL.trustAllHttpsCertificates();
            HttpsURLConnection.setDefaultHostnameVerifier(SSL.hv);
            Connection connect = Jsoup.connect(path);
            connect.response().cookies();
            connect.cookies(connect.response().cookies());
            connect.header("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:49.0) Gecko/20100101 Firefox/49.0")
                //如果是这种方式,这里务必带上
                .header("Connection", "close")
                .timeout(10000);
            return connect.get();
        } catch (Exception e) {
            System.out.println(url+"请求异常");
            log.error("请求异常:" + e);
            try {
                Thread.sleep(30000);
            } catch (InterruptedException ex) {
 
            }
            return connect(url);
        }
    }
 
    /**
     * version
     */
    private static String version() {
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
        String version = format.format(new Date());
        return version;
    }
 
    /**
     * 获取所有的省份(省级)
     * @param url 请求地址:https://www.stats.gov.cn/sj/tjbz/tjyqhdmhcxhfdm/2023/index.html
     * @return
     */
    private Boolean getProvinces(int count,String url) {
        List<Region> listAreas = new ArrayList<>();
        Document connect = connect(url);
        if(ObjectUtil.isEmpty(connect)||"请开启JavaScript并刷新该页.".equals(connect.select("strong").text())||"Please enable JavaScript and refresh the page.".equals(connect.select("strong").text())){
            try {
                Thread.sleep(60000);
            } catch (InterruptedException e) {
 
            }
            if(ObjectUtil.isNotNull(connect)){
                System.err.println(connect.toString());
            }
            System.err.println(url+"重试第"+(++count)+"次");
            getProvinces(count,url);
        }
        Elements rowProvince = connect.select("tr.provincetr");
        int i = 1;
        for (Element provinceElement : rowProvince) {
            Elements select = provinceElement.select("a");
            for (Element province : select) {
                String code = province.select("a").attr("href");
                String name = province.text();
                //if("江苏省".equals(name)){
                //if(!"北京市天津市河北省山西省内蒙古自治区辽宁省吉林省黑龙江省上海市江苏省浙江省安徽省福建省江西省山东省河南省".contains(name)){
                Region region = new Region();
                region.setCode(code.replace(".html",""));
                region.setName(name);
                region.setParentCode("00");
                region.setAncestors("00");
                region.setProvinceCode(code.replace(".html",""));
                region.setProvinceName(name);
//                region.setLevel(1);
//                region.setVersion(version());
                region.setSort(i++);
                listAreas.add(region);
 
                String provinceUrl = url.replace("index.html",code);
                // System.err.println("++++++++++++++++++++++++++开始获取"+ name +"下属市区行政区划信息++++++++++++++++++++++++");
                List<Region> cityAreaCodeList = getCityAreaCode(0,provinceUrl,region.getAncestors()+ "," +region.getCode(),region.getProvinceCode(),region.getProvinceName());
                listAreas.addAll(cityAreaCodeList);
 
                // 省级循环完毕后,插入数据库,并清空listAreas
                // logger.info(JSON.toJSONString(listAreas));
                System.err.println("*********************************开始插入【"+ name +"】行政区划*********************************");
                saveBatch(listAreas);
                listAreas = new ArrayList<>();
                System.err.println("*********************************结束插入【"+ name +"】行政区划*********************************");
                //}
            }
        }
        return true;
    }
 
    /**
     * 获取市一级行政区划代码(市级)
     * @param provinceUrl
     * @param provinceCode
     * @param provinceName
     * @param ancestors
     * @return
     */
    private List<Region> getCityAreaCode(int count,String provinceUrl, String ancestors,
                                            String provinceCode, String provinceName) {
        List<Region> listAreas = new ArrayList<>();
        Document connect = connect(provinceUrl);
 
        if(ObjectUtil.isEmpty(connect)||"请开启JavaScript并刷新该页.".equals(connect.select("strong").text())||"Please enable JavaScript and refresh the page.".equals(connect.select("strong").text())){
            try {
                Thread.sleep(30000);
            } catch (InterruptedException e) {
 
            }
            if(ObjectUtil.isNotNull(connect)){
                System.err.println(connect.toString());
            }
            System.err.println(provinceUrl+"重试第"+(++count)+"次");
            getCityAreaCode(count,provinceUrl,ancestors,provinceCode,provinceName);
        }
 
        Elements rowCity = connect.select("tr.citytr");
        int i = 1;
        for (Element cityElement : rowCity) {
            String name = cityElement.select("td").text();
            String[] split = name.split(" ");
            Region region = new Region();
            region.setCode(split[0].substring(0,4));
            region.setName(split[1]);
            region.setParentCode(provinceCode);
            region.setAncestors(ancestors);
            region.setProvinceCode(provinceCode);
            region.setProvinceName(provinceName);
            region.setCityCode(split[0].substring(0,4));
            region.setCityName(split[1]);
//            region.setLevel(2);
//            region.setVersion(version());
            region.setSort(i++);
 
            listAreas.add(region);
            String cityUrl = provinceUrl.replace(".html","/"+split[0].substring(0, 4)+".html");
            System.err.println("-------------------开始获取"+split[1]+"下属区县行政区划信息-----------------------");
            // System.out.println("市级url:"+cityUrl);
            List<Region> cityAreaCodeList = getCountyAreaCode(0,cityUrl,
                region.getAncestors()+ "," +region.getCode(),
                region.getProvinceCode(),
                region.getProvinceName(),
                region.getCityCode(),
                region.getCityName());
            listAreas.addAll(cityAreaCodeList);
        }
        return listAreas;
    }
 
    /**
     * 获取区县一级行政区划代码(区县级)
     * @param cityUrl
     * @param ancestors
     * @param provinceCode
     * @param provinceName
     * @param cityCode
     * @param cityName
     * @return
     */
    private List<Region> getCountyAreaCode(int count,String cityUrl, String ancestors,
                                              String provinceCode, String provinceName,
                                              String cityCode, String cityName){
        List<Region> listAreas = new ArrayList<>();
        Document connect = connect(cityUrl);
        if(ObjectUtil.isEmpty(connect)||"请开启JavaScript并刷新该页.".equals(connect.select("strong").text())||"Please enable JavaScript and refresh the page.".equals(connect.select("strong").text())){
            try {
                Thread.sleep(30000);
            } catch (InterruptedException e) {
 
            }
            if(ObjectUtil.isNotNull(connect)){
                System.err.println(connect.toString());
            }
            System.err.println(cityUrl+"重试第"+(++count)+"次");
            getCountyAreaCode(count,cityUrl,ancestors,provinceCode,provinceName,cityCode,cityName);
        }
        Elements rowCounty = connect.select("tr.countytr");
        int i = 1;
        for (Element countyElement : rowCounty) {
            String codeHtml = countyElement.select("a").attr("href");
            String name = countyElement.select("td").text();
            String[] split = name.split(" ");
            if(!"市辖区".equals(split[1])){
                Region region = new Region();
                region.setCode(split[0].substring(0,6));
                region.setName(split[1]);
                region.setParentCode(cityCode);
                region.setAncestors(ancestors);
                region.setProvinceCode(provinceCode);
                region.setProvinceName(provinceName);
                region.setCityCode(cityCode);
                region.setCityName(cityName);
                region.setDistrictCode(split[0].substring(0,6));
                region.setDistrictName(split[1]);
//                region.setLevel(3);
//                region.setVersion(version());
                region.setSort(i++);
 
                listAreas.add(region);
                String countyUrl = cityUrl.replace(region.getCityCode()+".html",codeHtml);
                if(!"金门县".equals(region.getDistrictName())){
                    System.err.println("====================开始获取"+split[1]+"下属区划信息");
                    // System.out.println("区县级url:"+cityUrl);
                    List<Region> countryAreaList = getDownAreaCode(0,countyUrl,
                        region.getAncestors()+ "," +region.getCode(),
                        region.getProvinceCode(),
                        region.getProvinceName(),
                        region.getCityCode(),
                        region.getCityName(),
                        region.getDistrictCode(),
                        region.getDistrictName());
                    listAreas.addAll(countryAreaList);
                }
            }
        }
        return listAreas;
    }
 
    /**
     * 获取乡镇街道数据(乡镇一级)
     * @param countyUrl
     * @param ancestors
     * @param provinceCode
     * @param provinceName
     * @param cityCode
     * @param cityName
     * @param countryCode
     * @param countryName
     * @return
     */
    private List<Region> getDownAreaCode(int count,String countyUrl, String ancestors,
                                            String provinceCode, String provinceName,
                                            String cityCode, String cityName,
                                            String countryCode, String countryName){
        List<Region> listAreas = new ArrayList<>();
        Document connect = connect(countyUrl);
        if(ObjectUtil.isEmpty(connect)||"请开启JavaScript并刷新该页.".equals(connect.select("strong").text())||"Please enable JavaScript and refresh the page.".equals(connect.select("strong").text())){
            try {
                Thread.sleep(30000);
            } catch (InterruptedException e) {
 
            }
            if(ObjectUtil.isNotNull(connect)){
                System.err.println(connect.toString());
            }
            System.err.println(countyUrl+"重试第"+(++count)+"次");
            getDownAreaCode(count,countyUrl,ancestors,provinceCode,provinceName,cityCode,cityName,countryCode,countryName);
        }
        Elements rowDown = connect.select("tr.towntr");
        int i = 1;
        for (Element downElement : rowDown) {
            String codeHtml = downElement.select("a").attr("href");
            String name = downElement.select("td").text();
            String[] split = name.split(" ");
            Region region = new Region();
            region.setCode(split[0].substring(0,9));
            region.setName(split[1]);
            region.setParentCode(countryCode);
            region.setAncestors(ancestors);
            region.setProvinceCode(provinceCode);
            region.setProvinceName(provinceName);
            region.setCityCode(cityCode);
            region.setCityName(cityName);
            region.setDistrictCode(countryCode);
            region.setDistrictName(countryName);
            region.setTownCode(split[0].substring(0,9));
            region.setTownName(split[1]);
//            region.setLevel(4);
//            region.setVersion(version());
            region.setSort(i++);
 
            listAreas.add(region);
            String downyUrl = countyUrl.replace(region.getDistrictCode()+".html",codeHtml);
            System.err.println("====================开始获取"+split[1]+"下属区划信息");
            //System.out.println("乡镇街道级URL:"+downyUrl);
            List<Region> villageAreaCodeList = getVillageAreaCode(0,downyUrl,
                region.getAncestors()+ "," +region.getCode(),
                region.getProvinceCode(),
                region.getProvinceName(),
                region.getCityCode(),
                region.getCityName(),
                region.getDistrictCode(),
                region.getDistrictName(),
                region.getTownCode(),
                region.getTownName());
            listAreas.addAll(villageAreaCodeList);
        }
        return listAreas;
    }
 
    private List<Region> getVillageAreaCode(int count,String downyUrl, String ancestors,
                                               String provinceCode, String provinceName,
                                               String cityCode, String cityName,
                                               String countryCode, String countryName,
                                               String townCode,String townName){
        List<Region> listAreas = new ArrayList<>();
        Document connect = connect(downyUrl);
        if(ObjectUtil.isEmpty(connect)||"请开启JavaScript并刷新该页.".equals(connect.select("strong").text())||"Please enable JavaScript and refresh the page.".equals(connect.select("strong").text())){
            try {
                Thread.sleep(30000);
            } catch (InterruptedException e) {
 
            }
            if(ObjectUtil.isNotNull(connect)){
                System.err.println(connect.toString());
            }
            System.err.println(downyUrl+"重试第"+(++count)+"次");
            getVillageAreaCode(count,downyUrl,ancestors,provinceCode,provinceName,cityCode,cityName,countryCode,countryName,townCode,townName);
        }
        Elements rowDown = connect.select("tr.villagetr");
        int i = 1;
        for (Element downElement : rowDown) {
            String name = downElement.select("td").text();
            String[] split = name.split(" ");
 
            Region region = new Region();
            region.setCode(split[0]);
            region.setName(split[2]);
            region.setParentCode(townCode);
            region.setAncestors(ancestors);
            region.setProvinceCode(provinceCode);
            region.setProvinceName(provinceName);
            region.setCityCode(cityCode);
            region.setCityName(cityName);
            region.setDistrictCode(countryCode);
            region.setDistrictName(countryName);
            region.setTownCode(townCode);
            region.setTownName(townName);
            region.setVillageCode(split[0]);
            region.setVillageName(split[2]);
//            region.setType(split[1]);
//            region.setLevel(5);
//            region.setVersion(version());
            region.setSort(i++);
 
            listAreas.add(region);
        }
        return listAreas;
    }
}