百度获取节日api:https://sp0.baidu.com/8aQDcjqpAAV3otqbppnN2DJv/api.php 参数:query:****年**月 resource_id:6018
只能获取当前年及之前的日期
接口层级:
代码的逻辑是先获取指定年份的所有周六、日的日期放入set<>中,再循环每个月调用百度api获取节假日日期,如果是放假则加到set中,如果要补班则删除set的日期
具体代码如下:
一、新建实体类 HolidayDTO.class
@Data
public class HolidayDTO {
private String desc;
private String festival;
private String name;
private String rest;
private List<HoliDTO> list;
}
HoliDTO.class
@Data
public class HoliDTO {
private String date;
private Integer status;
}
二、新建工具类DateUtils.class获取周六日
public class DateUtils{
public static Set<String> getSunDayAndStaurday(String year1){
int year = Integer.parseInt(year1);
Calendar calendar = new GregorianCalendar(year, Calendar.JANUARY, 1);
int i = 1;
Set<String> dates=new HashSet<>();
while (calendar.get(Calendar.YEAR) < year + 1) {
calendar.set(Calendar.WEEK_OF_YEAR, i++);
calendar.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
if (calendar.get(Calendar.YEAR) == year) {
dates.add(dateFormatYMD(calendar.getTime()));
}
calendar.set(Calendar.DAY_OF_WEEK, Calendar.SATURDAY);
if (calendar.get(Calendar.YEAR) == year) {
dates.add(dateFormatYMD(calendar.getTime()));
}
}
return dates;
}
}
三、生产节假日与周六日
public void getHoliday(String year) {
//获取一年的周六、日的日期
Set<String> holidayDate = DateUtils.getSunDayAndStaurday(year);
//循环调用百度api
for (int i = 1; i <= 12; i++) {
Map<String, String> parms = new HashMap<>();
parms.put("query", year + "年" + i + "月");
parms.put("resource_id", "6018");
String url = "https://sp0.baidu.com/8aQDcjqpAAV3otqbppnN2DJv/api.php";
String re = HttpClientUtils.getGetResult(url, parms, null);
//根据层级处理数据
JSONObject a = JSONObject.parseObject(re);
JSONArray b = a.getJSONArray("data");
JSONObject c = b.getJSONObject(0);
String d = c.getString("holiday");
List<HolidayDTO> holidayDTOList = new ArrayList<>();
if (StringUtils.isNotBlank(d)) {
//假如某个月没有节假日就不是数组
if (d.indexOf("[") == 0) {
holidayDTOList = JSONArray.parseArray(d, HolidayDTO.class);
} else {
HolidayDTO holidayDTO1 = JSONObject.parseObject(d, HolidayDTO.class);
holidayDTOList.add(holidayDTO1);
}
}
for (HolidayDTO holidayDTO : holidayDTOList) {
for (HoliDTO v : holidayDTO.getList()) {
if (v.getDate().contains(year)) {
//节假日放假增加到set
if (v.getStatus() == 1) {
holidayDate.add(DateUtils.dateFormatYMD(DateUtils.YMDDormatDate(v.getDate())));
}
//节假日补班则删除对应的日期
if (v.getStatus() == 2) {
if(holidayDate.contains(DateUtils.dateFormatYMD(DateUtils.YMDDormatDate(v.getDate())))) {
holidayDate.remove(DateUtils.dateFormatYMD(DateUtils.YMDDormatDate(v.getDate())));
}
}
}
}
}
}
//可以保存到数据库或者做其他作用
for (String v1 : holidayDate) {
HolidayDO holidayDO = new HolidayDO();
holidayDO.setDay(DateUtils.YMDDormatDate(v1));
holidayMapper.insert(holidayDO);
}
}