使用Hutool訪問和轉發bing每日壁紙

背景

我們知道Bing主頁每天都有變換的漂亮壁紙,通過解析可知其API地址是:

https://www.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1

其中:

  • format:返回內容格式,js表示JSON,xml表示XML,默認XML
  • idx:表示天數的位移,1表示昨天,0表示今天
  • n:表示張數

請求結果是:

{"images":[{"startdate":"20211121","fullstartdate":"202111211600","enddate":"20211122","url":"/th?id=OHR.IrohazakaRoad_ZH-CN9151363864_1920x1080.jpg&rf=LaDigue_1920x1080.jpg&pid=hp","urlbase":"/th?id=OHR.IrohazakaRoad_ZH-CN9151363864","copyright":"伊呂波坂山道,日本日光市 (© LightRecords/Shutterstock)","copyrightlink":"https://www.bing.com/search?q=%E4%BC%8A%E5%90%95%E6%B3%A2%E5%9D%82&form=hpcapt&mkt=zh-cn","title":"","quiz":"/search?q=Bing+homepage+quiz&filters=WQOskey:%22HPQuiz_20211121_IrohazakaRoad%22&FORM=HPQUIZ","wp":true,"hsh":"a9b142b3c3c4208185884c3c22303fc7","drk":1,"top":1,"bot":1,"hs":[]}],"tooltips":{"loading":"正在加載...","previous":"上一個圖像","next":"下一個圖像","walle":"此圖片不能下載用作壁紙。","walls":"下載今日美圖。僅限用作桌面壁紙。"}}

關鍵信息在這句:

"url":"/th?id=OHR.IrohazakaRoad_ZH-CN9151363864_1920x1080.jpg&rf=LaDigue_1920x1080.jpg&pid=hp"

拼接後:

https://www.bing.com/th?id=OHR.IrohazakaRoad_ZH-CN9151363864_1920x1080.jpg&rf=LaDigue_1920x1080.jpg&pid=hp

獲取

那麼接下來就簡單了,首先當然是引入Hutool

<dependency>
    <groupId>cn.hutool</groupId>
    <artifactId>hutool-all</artifactId>
    <version>5.7.16</version>
</dependency>

接下來兩句搞定:

String json = HttpUtil.get("https://www.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1");
String url = "https://www.bing.com" + ReUtil.getGroup1("\"url\":\"(.*?)\"", json);
Console.log(url);

說明:這裏沒有使用JSON模塊解析是因爲只是獲取一個屬性,使用正則速度更快!

發佈服務

最後就是Hutool提供的SimpleServer派上用場了!

HttpUtil.createServer(8087)
	.addAction("bing", (req, res) -> {
		String json = HttpUtil.get("https://www.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1");
		String url = "https://www.bing.com" + ReUtil.getGroup1("\"url\":\"(.*?)\"", json);
		res.write(url);
	}).start();

此時我們就可以訪問如下地址獲取到背景壁紙的真正地址了:

http://localhost:8087/bing

優化

當然,Bing的壁紙不能用戶每次來請求都去請求Bing的API吧,我們搞個簡單的緩存,完整代碼如下:

public class Main {

	private static String url;
	private static String today;

	public static void main(String[] args) {
		HttpUtil.createServer(8087)
				.addAction("bing", (req, res) -> {
					// 檢查緩存
					if (null == url || ObjectUtil.notEqual(today, DateUtil.today())) {
						url = getBingPicUrl();
						today = DateUtil.today();
					}

					res.write(url);
				}).start();
	}

	private static String getBingPicUrl() {
		final String json = HttpUtil.get("https://www.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1");
		final String url = ReUtil.getGroup1("\"url\":\"(.*?)\"", json);
		return "https://www.bing.com" + url;
	}
}

這樣,當天第一次請求後,就會直接返回緩存的URL了!

上線

哈哈,這個簡單的API服務已經上線到Hutool官網了哦!地址是:

http://plus.hutool.cn/bing

當然暫時沒配HTTPS,這個後續補充上。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章