Java获取节假日信息工具类(二)

2022年写的那个不知道由于网站做了改变,导致那个方法获取到的不对,故重新写一个供广大网友参考

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.Map;
import java.util.Set;

/**
 * 
 * ClassName: SaveHoliday.java 
* Description: 每年保存法定节假日
* Create Time: 2024年1月25日
*/ public class SaveHoliday { public static void main(String[] args) { syncHoliday(); } public static void syncHoliday() { String url = "https://timor.tech/api/holiday/year/"; BufferedReader reader = null; StringBuffer sbf = new StringBuffer(); try { URL realUrl = new URL(url); URLConnection connection = realUrl.openConnection(); connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); reader = new BufferedReader(new InputStreamReader(connection.getInputStream(),"UTF-8")); String line; while ((line = reader.readLine()) != null) { sbf.append(line); sbf.append("\r\n"); } reader.close(); } catch (IOException e) { e.printStackTrace(); } Map map = JSONObject.parseObject(sbf.toString()); if (map != null) { Integer code = (Integer) map.get("code"); if (code == 0) { JSONObject holidayJson = (JSONObject) map.get("holiday"); Set> entrySet = holidayJson.entrySet(); for (Map.Entry entry : entrySet) { String key = entry.getKey(); Object value = entry.getValue(); JSONObject object = JSONObject.parseObject(value.toString()); boolean holiday = object.getBoolean("holiday"); System.out.println(object); } } } } }

输出的数据如下:

{“date”:“2024-10-12”,“name”:“国庆节后补班”,“after”:true,“holiday”:false,“wage”:1,“target”:“国庆节”}

你可能感兴趣的:(java,开发语言)