做个后台登陆页面不好看,可以采集bing的(java sprin

2020-05-29  本文已影响0人  一块自由的砖

问题描述

辛辛苦苦做了个管理后台,登陆页面的背景太丑,不会自动变化。不要紧。亲测了代码可以使用

实现

前端使用方法

.login {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100%;
    background-image:url(http://自己服务器的网址|IP/clientapi/bingimage/getImage);
    background-size: cover;
  }

后端代码实现

package clientapi.rest;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.util.Objects;

/**
 * @author Horace pei
 * @date 2020-3-12
 */
@RestController
@RequestMapping("/clientapi/bingimage")
public class ApiBingImageController {
    //获取bing背景图片接口
    @GetMapping(value = "/getImage")
    public void getInfo(HttpServletResponse response) throws IOException {
        JSONObject object = getUrl();
        String url = "https://cn.bing.com"
                + object.getJSONArray("images").getJSONObject(0).getString("url");
        Objects.requireNonNull(doGetEntity(url)).writeTo(response.getOutputStream());
        response.setContentType("image/jpg");
    }
    //获取图片信息对应json信息
    private JSONObject getUrl() {
        String json = doGet("https://cn.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1&mkt=zh-CN");
        return JSON.parseObject(json);
    }

    private String doGet(String url) {
        return getString(url);
    }

    private String getString(String url) {
        String result = "";
        try {
            HttpGet httpGet = new HttpGet(url);
            HttpClient client = HttpClients.createDefault();
            HttpResponse response = client.execute(httpGet);
            HttpEntity entity = response.getEntity();
            result = EntityUtils.toString(entity);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
    //读取bing网址图片数据
    private HttpEntity doGetEntity(String url) {
        return getHttpEntity(url);
    }

    private static HttpEntity getHttpEntity(String url) {
        try {
            HttpGet httpGet = new HttpGet(url);
            HttpClient client = HttpClients.createDefault();
            HttpResponse response = client.execute(httpGet);
            response.getEntity().getContent();
            return response.getEntity();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}

如果bing一直不改变接口返回值的话,可以一直用着。有些不错的图可以采集回来做桌面背景也是不错的。

上一篇 下一篇

猜你喜欢

热点阅读